#!/usr/bin/env node
/**
 * cli:efcore-squash — Consolidate branch-only migrations into one.
 *
 * Steps (per assembly of the target context):
 *   1. Backup branch-only migrations + snapshot to .efcore-squash-backup/
 *   2. Delete branch-only migration files (+ .Designer.cs)
 *   3. Reset ModelSnapshot.cs to match the base branch
 *   4. Run `dotnet ef migrations add <consolidated_name>` to regenerate
 *
 * Refuses to run on main/master.
 *
 * Usage:
 *   npx tsx skills/efcore/cli/squash/index.ts --spec '{
 *     "cwd": "...",
 *     "contextName": "CoreDbContext",
 *     "description": "FeatureXYZConsolidated"
 *   }'
 */
import { parseArgs } from 'node:util';
import { existsSync, readFileSync } from 'node:fs';
import { validate } from './validate.js';
import { execute } from './execute.js';

async function main(): Promise<void> {
  const { values } = parseArgs({
    options: {
      spec: { type: 'string' },
      help: { type: 'boolean', short: 'h' },
    },
  });

  if (values.help || !values.spec) {
    console.log(`Usage: npx tsx skills/efcore/cli/squash/index.ts --spec '{"cwd":"...","contextName":"CoreDbContext","description":"FooConsolidated"}'`);
    process.exit(values.help ? 0 : 1);
  }

  let raw: unknown;
  try {
    raw = existsSync(values.spec!) ? JSON.parse(readFileSync(values.spec!, 'utf-8')) : JSON.parse(values.spec!);
  } catch (err) {
    console.log(JSON.stringify({ success: false, error: `Invalid JSON: ${(err as Error).message}` }, null, 2));
    process.exit(1);
  }

  const validation = validate(raw);
  if (!validation.valid || !validation.data) {
    console.log(JSON.stringify({ success: false, errors: validation.blockers, warnings: validation.warnings }, null, 2));
    process.exit(1);
  }

  const result = await execute(validation.data);
  console.log(JSON.stringify(result, null, 2));
  process.exit(result.success ? 0 : 1);
}

void main();
