// --- Helpers ---
function extractAcceptanceCriteria(specContent) {
    const criteria = [];
    const lines = specContent.split('\n');
    let acIndex = 0;
    for (const line of lines) {
        const match = /^-\s*\[[ x]\]\s*(.+)$/i.exec(line);
        if (match?.[1]) {
            acIndex++;
            criteria.push({ id: `AC-${String(acIndex)}`, text: match[1].trim() });
        }
    }
    return criteria;
}
function acToGivenWhenThen(text) {
    // Best-effort heuristic: if AC is behavioral, map to Given/When/Then
    const lower = text.toLowerCase();
    if (lower.includes(' when ') || lower.includes(' if ')) {
        return `- Given the system is ready\n  - When ${text}\n  - Then the expected outcome occurs`;
    }
    return `- Given the system is ready\n  - When the user triggers: ${text}\n  - Then the feature works as specified`;
}
function generateYamlFrontmatter(spec) {
    const lines = ['---'];
    lines.push(`title: "${spec.title}"`);
    lines.push(`planu_id: "${spec.id}"`);
    lines.push(`type: ${spec.type}`);
    lines.push(`scope: ${spec.scope}`);
    lines.push(`status: ${spec.status}`);
    lines.push(`risk: ${spec.risk}`);
    lines.push(`difficulty: ${String(spec.difficulty)}`);
    if (spec.tags.length > 0) {
        lines.push(`tags: [${spec.tags.map((t) => `"${t}"`).join(', ')}]`);
    }
    lines.push(`estimated_hours: ${String(spec.estimation.devHours + spec.estimation.reviewHours)}`);
    lines.push('---');
    return lines.join('\n');
}
// --- Public API ---
export function generateSpecKitSpec(spec, specContent, _constitution) {
    const lines = [];
    const frontmatter = generateYamlFrontmatter(spec);
    lines.push(frontmatter);
    lines.push('');
    lines.push(`# ${spec.title}`);
    lines.push('');
    // User Scenarios
    lines.push('## User Scenarios');
    lines.push('');
    const sections = extractSections(specContent);
    const description = sections.summary ?? sections.description ?? spec.title;
    lines.push(description);
    lines.push('');
    // Acceptance Scenarios (Given/When/Then)
    const criteria = extractAcceptanceCriteria(specContent);
    if (criteria.length > 0) {
        lines.push('## Acceptance Scenarios');
        lines.push('');
        for (const ac of criteria) {
            lines.push(`### ${ac.id}`);
            lines.push(acToGivenWhenThen(ac.text));
            lines.push('');
        }
    }
    // Functional Requirements
    if (criteria.length > 0) {
        lines.push('## Functional Requirements');
        lines.push('');
        for (const ac of criteria) {
            const frId = ac.id.replace('AC-', 'FR-');
            lines.push(`- **${frId}**: ${ac.text}`);
        }
        lines.push('');
    }
    // Success Criteria
    lines.push('## Success Criteria');
    lines.push('');
    if (criteria.length > 0) {
        lines.push(`- All ${String(criteria.length)} acceptance criteria pass`);
    }
    lines.push('- No regressions introduced');
    lines.push('- Code passes type checking and linting');
    lines.push('');
    // Planu marker for round-trip
    lines.push(`<!-- planu:${spec.id} -->`);
    return lines.join('\n');
}
export function generateSpecKitPlan(spec, technicalContent, constitution, filePlan) {
    const lines = [];
    lines.push(`# Plan: ${spec.title}`);
    lines.push('');
    // Technical Context
    if (technicalContent) {
        lines.push('## Technical Context');
        lines.push('');
        const techSections = extractSections(technicalContent);
        if (techSections.architecture) {
            lines.push('### Architecture');
            lines.push(techSections.architecture);
            lines.push('');
        }
        if (techSections['key decisions']) {
            lines.push('### Key Decisions');
            lines.push(techSections['key decisions']);
            lines.push('');
        }
        // Fallback: if no recognized sections, include full content
        if (!techSections.architecture && !techSections['key decisions']) {
            lines.push(technicalContent.replace(/^#\s+.+\n/, '').trim());
            lines.push('');
        }
    }
    // Language/Version, Dependencies, Storage, Testing
    lines.push('## Implementation Details');
    lines.push('');
    lines.push(`- **Type**: ${spec.type}`);
    lines.push(`- **Scope**: ${spec.scope}`);
    lines.push(`- **Target**: ${spec.target}`);
    lines.push(`- **Estimated Hours**: ${String(spec.estimation.devHours + spec.estimation.reviewHours)}`);
    lines.push('');
    // Project Structure from file plan
    if (filePlan && filePlan.length > 0) {
        lines.push('## Project Structure');
        lines.push('');
        lines.push('```');
        for (const file of filePlan) {
            lines.push(file);
        }
        lines.push('```');
        lines.push('');
    }
    // Constitution Check
    if (constitution) {
        lines.push('## Constitution Check');
        lines.push('');
        lines.push(constitution);
        lines.push('');
    }
    lines.push(`<!-- planu:${spec.id} -->`);
    return lines.join('\n');
}
export function generateSpecKitTasks(spec, specContent) {
    const lines = [];
    lines.push(`# Tasks: ${spec.title}`);
    lines.push('');
    const criteria = extractAcceptanceCriteria(specContent);
    if (criteria.length === 0) {
        lines.push('No tasks derived — no acceptance criteria found.');
        lines.push('');
        lines.push(`<!-- planu:${spec.id} -->`);
        return lines.join('\n');
    }
    // Phase organization
    const phases = categorizeTasks(criteria);
    for (const phase of phases) {
        lines.push(`## ${phase.name}`);
        lines.push('');
        for (const task of phase.tasks) {
            const parallel = phase.name !== 'Setup' ? ' [P]' : '';
            lines.push(`- [ ] ${task.text} [${task.id}]${parallel}`);
        }
        lines.push('');
    }
    lines.push(`<!-- planu:${spec.id} -->`);
    return lines.join('\n');
}
export function exportToSpecKit(spec, specContent, options = {}) {
    return {
        specMd: generateSpecKitSpec(spec, specContent, options.constitution),
        planMd: generateSpecKitPlan(spec, options.technicalContent, options.constitution, options.filePlan),
        tasksMd: generateSpecKitTasks(spec, specContent),
    };
}
// --- Internal helpers ---
function extractSections(content) {
    const sections = {};
    const lines = content.split('\n');
    let currentHeading = '';
    let currentContent = [];
    for (const line of lines) {
        const headingMatch = /^#{1,3}\s+(.+)/.exec(line);
        if (headingMatch?.[1]) {
            if (currentHeading && currentContent.length > 0) {
                sections[currentHeading] = currentContent.join('\n').trim();
            }
            currentHeading = headingMatch[1].toLowerCase();
            currentContent = [];
        }
        else {
            currentContent.push(line);
        }
    }
    if (currentHeading && currentContent.length > 0) {
        sections[currentHeading] = currentContent.join('\n').trim();
    }
    return sections;
}
function categorizeTasks(criteria) {
    const setup = { name: 'Setup', tasks: [] };
    const core = { name: 'Core', tasks: [] };
    const integration = { name: 'Integration', tasks: [] };
    const polish = { name: 'Polish', tasks: [] };
    for (const ac of criteria) {
        const lower = ac.text.toLowerCase();
        if (lower.includes('register') ||
            lower.includes('create') ||
            lower.includes('setup') ||
            lower.includes('schema')) {
            setup.tasks.push(ac);
        }
        else if (lower.includes('test') || lower.includes('document') || lower.includes('clean')) {
            polish.tasks.push(ac);
        }
        else if (lower.includes('output') ||
            lower.includes('write') ||
            lower.includes('return') ||
            lower.includes('directory')) {
            integration.tasks.push(ac);
        }
        else {
            core.tasks.push(ac);
        }
    }
    // Filter out empty phases
    return [setup, core, integration, polish].filter((p) => p.tasks.length > 0);
}
//# sourceMappingURL=spec-kit-exporter.js.map