#!/usr/bin/env node
import { createCiPlan } from "./src/ci-plan-lib.mjs";

const args = parseArgs(process.argv.slice(2));

if (args.help) {
  process.stdout.write(`${usage()}\n`);
  process.exit(0);
}

const plan = await createCiPlan(args);
process.stdout.write(args.pretty ? `${JSON.stringify(plan, null, 2)}\n` : `${JSON.stringify(plan)}\n`);

function parseArgs(argv) {
  const parsed = { pretty: false };
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    if (arg === "--base-ref") parsed.baseRef = readOption(argv, ++index, arg);
    else if (arg === "--target-ref") parsed.targetRef = readOption(argv, ++index, arg);
    else if (arg === "--deploy-config") parsed.deployConfigPath = readOption(argv, ++index, arg);
    else if (arg === "--artifact-catalog") parsed.artifactCatalogPath = readOption(argv, ++index, arg);
    else if (arg === "--lane") parsed.lane = readOption(argv, ++index, arg);
    else if (arg === "--registry-prefix") parsed.registryPrefix = readOption(argv, ++index, arg);
    else if (arg === "--verify-reuse-registry") parsed.verifyReuseRegistry = true;
    else if (arg === "--no-verify-reuse-registry") parsed.verifyReuseRegistry = false;
    else if (arg === "--base-image") parsed.baseImage = readOption(argv, ++index, arg);
    else if (arg === "--services") parsed.services = readOption(argv, ++index, arg).split(",").map((item) => item.trim()).filter(Boolean);
    else if (arg === "--pretty") parsed.pretty = true;
    else if (arg === "--help" || arg === "-h") parsed.help = true;
    else throw new Error(`unknown argument ${arg}`);
  }
  return parsed;
}

function readOption(argv, index, name) {
  const value = argv[index];
  if (!value || value.startsWith("--")) throw new Error(`${name} requires a value`);
  return value;
}

function usage() {
  return [
    "usage: node scripts/ci-plan.mjs [--lane v02|v03] [--base-ref REF] [--target-ref REF] [--verify-reuse-registry] [--pretty]",
    "",
    "Plan node monorepo image builds without mutating CI/CD state.",
    "For runtime lane env reuse, service component boundaries and env recipe must come from deploy/deploy.yaml.",
    "",
    "examples:",
    "  node scripts/ci-plan.mjs --lane v02 --base-ref HEAD~1 --target-ref HEAD --pretty",
    "  node scripts/ci-plan.mjs --lane v03 --base-ref HEAD~1 --target-ref HEAD --pretty",
    "  node scripts/ci-plan.mjs --services hwlab-cloud-api,hwlab-cloud-web --pretty"
  ].join("\n");
}
