import { readFile } from "node:fs/promises";
import { prisma } from "../db.js";
import { importLegacyProjects, type LegacyProjectManifestEntry } from "./legacyProjectImport.js";
import { readSiloOrganizationId } from "./silo.js";

async function main(argv: readonly string[]): Promise<void> {
  const options = parseOptions(argv);
  const organizationId = readSiloOrganizationId();
  const manifest = JSON.parse(await readFile(required(options, "manifest"), "utf8")) as unknown;
  if (!Array.isArray(manifest)) throw new Error("legacy import manifest must be a JSON array");
  const state = await importLegacyProjects({
    prisma,
    organizationId,
    actorFeishuOpenId: required(options, "actor-open-id"),
    workspaceRoot: required(options, "workspace-root"),
    sourceRoot: required(options, "source-root"),
    stateFile: required(options, "state-file"),
    projects: manifest as LegacyProjectManifestEntry[],
    onProgress: (message) => console.error(`[legacy-import] ${message}`),
  });
  console.log(JSON.stringify({ imported: Object.keys(state.projects).length }));
}

function parseOptions(args: readonly string[]): Map<string, string> {
  const options = new Map<string, string>();
  for (let index = 0; index < args.length; index += 2) {
    const flag = args[index];
    const value = args[index + 1];
    if (flag === undefined || !flag.startsWith("--") || value === undefined) {
      throw new Error(`expected --name value, got: ${args.slice(index).join(" ")}`);
    }
    options.set(flag.slice(2), value);
  }
  return options;
}

function required(options: ReadonlyMap<string, string>, name: string): string {
  const value = options.get(name)?.trim();
  if (!value) throw new Error(`--${name} is required`);
  return value;
}

main(process.argv.slice(2))
  .catch((error) => {
    console.error(error instanceof Error ? error.message : String(error));
    process.exitCode = 1;
  })
  .finally(async () => prisma.$disconnect());
