import { specStore } from '../storage/index.js';
import { planTeamDistribution } from '../engine/team-planner/index.js';
import { readFile } from 'node:fs/promises';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function text(content) {
    return { content: [{ type: 'text', text: JSON.stringify(content, null, 2) }] };
}
function err(message) {
    return { content: [{ type: 'text', text: message }], isError: true };
}
/** Extract acceptance criteria lines from a spec.md file. */
async function extractCriteria(specPath) {
    try {
        const content = await readFile(specPath, 'utf-8');
        const criteria = [];
        let inCriteria = false;
        for (const line of content.split('\n')) {
            if (/acceptance\s+criteria/i.test(line) || /criterios?\s+de\s+aceptaci/i.test(line)) {
                inCriteria = true;
                continue;
            }
            if (inCriteria && /^#{1,3}\s/.test(line) && !/acceptance|criterio/i.test(line)) {
                break;
            }
            if (inCriteria && /^\s*[-*]\s*\[.\]/.test(line)) {
                criteria.push(line.replace(/^\s*[-*]\s*\[.\]\s*/, '').trim());
            }
        }
        return criteria;
        /* v8 ignore next 3 -- defensive: spec file may not exist on disk */
    }
    catch {
        return [];
    }
}
/** Extract file paths from a technical.md file. */
async function extractFiles(technicalPath) {
    try {
        const content = await readFile(technicalPath, 'utf-8');
        const files = [];
        const filePattern = /`((?:src|tests)\/[^`]+\.(?:ts|js|tsx|jsx))`/g;
        let match = filePattern.exec(content);
        while (match !== null) {
            const filePath = match[1];
            if (filePath !== undefined) {
                files.push(filePath);
            }
            match = filePattern.exec(content);
        }
        return [...new Set(files)];
        /* v8 ignore next 3 -- defensive: technical file may not exist on disk */
    }
    catch {
        return [];
    }
}
// ---------------------------------------------------------------------------
// Pre-built templates
// ---------------------------------------------------------------------------
const TEMPLATES = [
    {
        id: 'implement-and-test',
        name: 'Implement + Test',
        description: 'One implementer and one tester per spec.',
        pattern: 'parallel-pairs',
        roles: [
            { role: 'implementer', model: 'sonnet', count: 'per-spec' },
            { role: 'tester', model: 'sonnet', count: 'per-spec' },
        ],
    },
    {
        id: 'full-stack',
        name: 'Full Stack',
        description: 'Researcher + implementers + testers.',
        pattern: 'phased',
        roles: [
            { role: 'researcher', model: 'opus', count: 1 },
            { role: 'implementer', model: 'sonnet', count: 'per-spec' },
            { role: 'tester', model: 'sonnet', count: 'per-spec' },
        ],
    },
    {
        id: 'research-then-build',
        name: 'Research Then Build',
        description: 'Deep research phase followed by parallel implementation.',
        pattern: 'sequential',
        roles: [
            { role: 'researcher', model: 'opus', count: 1 },
            { role: 'implementer', model: 'sonnet', count: 'per-spec' },
        ],
    },
    {
        id: 'parallel-specs',
        name: 'Parallel Specs',
        description: 'Each spec gets an independent implementer — maximum parallelism.',
        pattern: 'fan-out',
        roles: [{ role: 'implementer', model: 'sonnet', count: 'per-spec' }],
    },
];
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handlePlanTeamDistribution(params) {
    const { projectId, specIds, template } = params;
    if (specIds.length === 0) {
        return err('specIds must contain at least one spec ID. Provide the specs to distribute.');
    }
    const specDetails = [];
    const fileOwnership = {};
    for (const specId of specIds) {
        const spec = await specStore.getSpec(projectId, specId);
        if (!spec) {
            return err(`Spec '${specId}' not found in project '${projectId}'. Check the spec ID.`);
        }
        const criteria = await extractCriteria(spec.specPath);
        const files = await extractFiles(spec.technicalPath);
        specDetails.push({ id: spec.id, title: spec.title, criteria });
        fileOwnership[spec.id] = files;
    }
    // Resolve template
    const teamTemplate = template ? TEMPLATES.find((t) => t.id === template) : undefined;
    if (template && !teamTemplate) {
        const validIds = TEMPLATES.map((t) => t.id).join(', ');
        return err(`Template '${template}' not found. Valid templates: ${validIds}.`);
    }
    const plan = planTeamDistribution(specDetails, fileOwnership, teamTemplate);
    return text(plan);
}
//# sourceMappingURL=plan-team-distribution.js.map