#!/usr/bin/env node

/**
 * commit CLI — Commit changes with optional EF Core validation and push
 */

import { parseArgs } from 'node:util';
import { validate } from './validate.js';
import { execute } from './execute.js';
import { CommitResultSchema } from './types.js';

async function main() {
  try {
    const args = parseArgs({
      options: {
        spec: { type: 'string' },
        json: { type: 'boolean', default: false },
      },
      allowPositionals: false,
    });

    if (!args.values.spec) {
      console.error('Error: --spec is required');
      process.exit(2);
    }

    let specObj: unknown;
    try {
      specObj = JSON.parse(args.values.spec);
    } catch {
      console.error('Error: --spec must be valid JSON');
      process.exit(2);
    }

    const validation = validate(specObj);
    if (!validation.valid) {
      if (args.values.json) {
        console.log(JSON.stringify({
          success: false,
          error: validation.blockers.join('; '),
        }, null, 2));
      } else {
        console.error('Validation failed:');
        validation.blockers.forEach(b => console.error(`  - ${b}`));
      }
      process.exit(2);
    }

    const result = await execute(validation.data!);
    const validated = CommitResultSchema.parse(result);

    if (args.values.json) {
      console.log(JSON.stringify(validated, null, 2));
    } else {
      if (validated.success) {
        console.log(`✓ Commit ${validated.commit?.hash.slice(0, 7)} created`);
        console.log(`  Message: ${validated.commit?.message}`);
        console.log(`  Files changed: ${validated.filesChanged}`);
        if (validated.pushed) {
          console.log(`  Pushed to origin`);
        }
        if (validated.efcore?.detected) {
          console.log(`  EF Core: ${validated.efcore.migrations.length} migrations`);
        }
      } else {
        console.error(`✗ ${validated.error}`);
      }
    }

    process.exit(validated.success ? 0 : 1);
  } catch (err: unknown) {
    console.error('Fatal error:', (err as Error).message);
    process.exit(2);
  }
}

main();
