import fs from "node:fs";
import path from "node:path";
import { ProgressInput, ProgressEntry } from "../../../progress/schema";
import { type CommandResult, success, failure } from "../../lib/command-result";
import { getGitContext } from "./git-context";

export function runProgressLog(jsonInput: string, dryRun: boolean, cwd: string): CommandResult {
  let parsed: unknown;
  try {
    parsed = JSON.parse(jsonInput);
  } catch {
    return failure("Invalid JSON input");
  }

  const inputResult = ProgressInput.safeParse(parsed);
  if (!inputResult.success) {
    const issues = inputResult.error.issues
      .map((i) => `${i.path.join(".")}: ${i.message}`)
      .join(", ");
    return failure(`Invalid progress input: ${issues}`);
  }

  const enriched = {
    ...inputResult.data,
    timestamp: new Date().toISOString(),
    git: getGitContext(cwd),
  };

  const entryResult = ProgressEntry.safeParse(enriched);
  if (!entryResult.success) {
    const issues = entryResult.error.issues
      .map((i) => `${i.path.join(".")}: ${i.message}`)
      .join(", ");
    return failure(`Invalid progress entry after enrichment: ${issues}`);
  }

  const line = JSON.stringify(entryResult.data);
  console.log(line);

  if (dryRun) {
    return success();
  }

  const erpKitDir = path.join(cwd, ".erp-kit");
  fs.mkdirSync(erpKitDir, { recursive: true });
  fs.appendFileSync(path.join(erpKitDir, "progress.jsonl"), line + "\n", "utf-8");

  return success();
}
