import { specStore } from '../../storage/index.js';
import { ti } from '../../i18n/index.js';
import { git, resolveProjectPath } from './git-helpers.js';
export async function handleGeneratePr(projectId, specId) {
    if (!specId) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ error: 'specId is required for generate-pr action' }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const projectPath = await resolveProjectPath(projectId);
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [
                { type: 'text', text: JSON.stringify({ error: `Spec '${specId}' not found` }, null, 2) },
            ],
            isError: true,
        };
    }
    const { stdout: currentBranch } = await git(projectPath, ['rev-parse', '--abbrev-ref', 'HEAD']);
    const branch = currentBranch.trim();
    let baseBranch = 'main';
    try {
        await git(projectPath, ['rev-parse', '--verify', 'main']);
    }
    catch {
        try {
            await git(projectPath, ['rev-parse', '--verify', 'master']);
            baseBranch = 'master';
        }
        catch {
            baseBranch = 'HEAD~10';
        }
    }
    let commitLog;
    try {
        const { stdout } = await git(projectPath, [
            'log',
            `${baseBranch}..HEAD`,
            '--oneline',
            '--no-decorate',
        ]);
        commitLog = stdout.trim();
    }
    catch {
        commitLog = '(unable to determine commits)';
    }
    let changedFiles;
    try {
        const { stdout } = await git(projectPath, ['diff', '--name-only', `${baseBranch}...HEAD`]);
        changedFiles = stdout.trim();
    }
    catch {
        changedFiles = '(unable to determine changed files)';
    }
    const typeLabel = spec.type.charAt(0).toUpperCase() + spec.type.slice(1);
    const prTitle = `[${specId}] ${spec.title}`;
    // Build acceptance criteria checklist from spec (criteria live in HU.md, not on spec object)
    const criteriaChecklist = buildCriteriaChecklist();
    const prBody = [
        `## ${typeLabel}: ${spec.title}`,
        '',
        `**Spec:** \`${specId}\``,
        `**Branch:** \`${branch}\``,
        `**Scope:** ${spec.scope}`,
        `**Difficulty:** ${spec.difficulty}/5`,
        `**Risk:** ${spec.risk}`,
        '',
        '## Description',
        '',
        `Implements spec ${specId} — ${spec.title}.`,
        '',
        '## Changes',
        '',
        changedFiles
            ? changedFiles
                .split('\n')
                .map((f) => `- \`${f}\``)
                .join('\n')
            : '- (no changes detected)',
        '',
        '## Commits',
        '',
        commitLog
            ? commitLog
                .split('\n')
                .map((c) => `- ${c}`)
                .join('\n')
            : '- (no commits detected)',
        '',
        '## Acceptance Criteria',
        '',
        criteriaChecklist,
        '',
        '## Verification Checklist',
        '',
        '- [ ] All acceptance criteria from spec met',
        '- [ ] Tests pass',
        '- [ ] No drift from spec',
        '- [ ] Code review completed',
        spec.impactAnalysis?.requiresMigration ? '- [ ] Migration tested' : null,
        spec.impactAnalysis?.requiresFeatureFlag ? '- [ ] Feature flag configured' : null,
        '',
        `## Estimation vs Actuals`,
        '',
        `| Metric | Estimated | Actual |`,
        `|--------|-----------|--------|`,
        `| Dev Hours | ${spec.estimation.devHours} | TBD |`,
        `| Total Cost | $${spec.estimation.totalCostUsd.toFixed(2)} | TBD |`,
        '',
        `---`,
        `*Generated by Planu SDD*`,
    ]
        .filter((line) => line !== null)
        .join('\n');
    const labels = buildLabels(spec.type, spec.risk, spec.scope);
    const prTemplate = {
        title: prTitle,
        body: prBody,
        labels,
    };
    const result = {
        action: 'generate-pr',
        branchName: branch,
        prTemplate,
        message: ti('tools.manage_git.success', { action: 'generate-pr' }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
function buildCriteriaChecklist() {
    return '- [ ] All acceptance criteria met (see HU.md)';
}
function buildLabels(type, risk, scope) {
    const labels = [];
    // Map spec type to PR label
    const typeMap = {
        feature: 'enhancement',
        bugfix: 'bug',
        refactor: 'refactor',
        infra: 'infrastructure',
        docs: 'documentation',
        project: 'project',
    };
    labels.push(typeMap[type] ?? type);
    if (risk === 'high' || risk === 'critical') {
        labels.push(`risk:${risk}`);
    }
    if (scope === 'architectural' || scope === 'cross-module') {
        labels.push(`scope:${scope}`);
    }
    return labels;
}
//# sourceMappingURL=pr-ops.js.map