/**
 * generate-msg CLI execute — Formalize Claude's analysis into a conventional commit message
 *
 * Receives structured analysis from the Skill (Claude) and produces
 * a formatted commit message in Markdown with conventional commits header.
 */

import type { GenerateMsgSpec, GenerateMsgResult } from './types.js';

const TYPE_MAP: Record<string, string> = {
  feature: 'feat',
  hotfix: 'fix',
  release: 'chore',
  develop: 'chore',
  main: 'chore',
  other: 'chore',
};

export async function execute(spec: GenerateMsgSpec): Promise<GenerateMsgResult> {
  try {
    const type = TYPE_MAP[spec.branchType] || 'chore';
    const scope = spec.scope ? `(${spec.scope})` : '';
    const header = `${type}${scope}: ${spec.summary}`;

    // Build MD body from file analysis
    const lines: string[] = [header];

    if (spec.files.length > 0) {
      lines.push('');
      for (const file of spec.files) {
        const icon = file.status === 'added' ? '+' : file.status === 'deleted' ? '-' : '~';
        lines.push(`- ${icon} \`${file.path}\`: ${file.summary}`);
      }
    }

    if (spec.breaking) {
      lines.push('');
      lines.push(`BREAKING CHANGE: ${spec.breaking}`);
    }

    const message = lines.join('\n');

    return { success: true, message };
  } catch (err: unknown) {
    return {
      success: false,
      error: (err as Error).message,
      message: '',
    };
  }
}
