const path = require("path");
const { planUpgrade, applyUpgrade } = require("../lib/upgrade-matrix");

function pkgRoot() {
  return path.join(__dirname, "..", "..");
}

module.exports = async function upgrade(flags = {}) {
  const rootDir = process.cwd();
  const dryRun = !flags.apply;
  const plan = planUpgrade(rootDir, pkgRoot());

  if (plan.error) {
    console.error(plan.error);
    process.exit(1);
  }

  if (flags.json) {
    console.log(
      JSON.stringify(
        {
          dry_run: dryRun,
          project_schema: plan.project_schema,
          package_schema: plan.package_schema,
          conflicts: plan.conflicts,
          custom_preserved: plan.custom_preserved,
          summary: plan.summary
        },
        null,
        2
      )
    );
    if (dryRun) return;
  } else {
    console.log("\n## CapInt Upgrade (matrix)\n");
    console.log(`Project schema: ${plan.project_schema}`);
    console.log(`Package schema: ${plan.package_schema}`);
    console.log(`\n${plan.summary}\n`);

    if (plan.custom_preserved.length) {
      console.log("Custom preserved task_types:");
      for (const id of plan.custom_preserved) console.log(`  + ${id}`);
      console.log("");
    }

    if (plan.conflicts.length) {
      console.log("Conflicts (package wins on --apply):");
      for (const c of plan.conflicts) {
        console.log(`  ${c.id}.${c.field}`);
        console.log(`    project: ${JSON.stringify(c.project_value)}`);
        console.log(`    package: ${JSON.stringify(c.package_value)}`);
      }
      console.log("");
    } else {
      console.log("No field conflicts.\n");
    }
  }

  if (dryRun) {
    if (!flags.json) console.log("Dry-run — use --apply to write backup + update matrix.\n");
    return;
  }

  const backup = applyUpgrade(rootDir, plan.merged, pkgRoot());
  if (!flags.json) {
    console.log(`Backup: ${path.relative(rootDir, backup)}`);
    console.log(`Matrix + registry updated; skills/workflows synced (${listPackageSkillNames(pkgRoot()).length} skills in package).\n`);
  }
};
