#!/usr/bin/env node

/**
 * generate-msg CLI — Formalize commit message from Claude's analysis
 *
 * Input: JSON spec with branch info + Claude's per-file analysis
 * Output: Formatted conventional commit message in Markdown
 */

import { parseArgs } from 'node:util';
import { validate } from './validate.js';
import { execute } from './execute.js';
import { GenerateMsgResultSchema } 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('; '),
          message: '',
        }, 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 = GenerateMsgResultSchema.parse(result);

    if (args.values.json) {
      console.log(JSON.stringify(validated, null, 2));
    } else {
      if (validated.success) {
        console.log(validated.message);
      } else {
        console.error(`Error: ${validated.error}`);
      }
    }

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

main();
