#!/usr/bin/env bun
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { assembleLiveReport, renderLiveReportHtml } from "../src/live-report";

function readArg(name: string): string | undefined {
  const index = process.argv.indexOf(name);
  if (index === -1) return undefined;
  return process.argv[index + 1];
}

function repoRoot(): string {
  return resolve(readArg("--repo") ?? join(dirname(new URL(import.meta.url).pathname), "..", ".."));
}

function sourceRevision(root: string): string {
  try {
    return execFileSync("git", ["-C", root, "rev-parse", "HEAD"], {
      encoding: "utf8",
    }).trim();
  } catch {
    return "unknown";
  }
}

function defaultOutputPath(): string {
  const reportsDir =
    process.env.OVERDECK_REPORTS_DIR ?? join(homedir(), ".local", "share", "overdeck", "reports");
  return join(reportsDir, "2026-08-08-session-report.html");
}

const root = repoRoot();
const generatedAt = readArg("--generated-at") ?? new Date().toISOString();
const outputPath = resolve(readArg("--output") ?? defaultOutputPath());
const jsonOnly = process.argv.includes("--json");

const data = assembleLiveReport({
  repoRoot: root,
  generatedAt,
  sourceRevision: sourceRevision(root),
});

if (jsonOnly) {
  console.log(JSON.stringify(data, null, 2));
  process.exit(0);
}

const html = renderLiveReportHtml(data);
mkdirSync(dirname(outputPath), { recursive: true });
writeFileSync(outputPath, html, "utf8");
console.log(outputPath);
