import { specStore, knowledgeStore } from '../storage/index.js';
import { buildTeammatePrompt } from '../engine/team-planner/index.js';
import { generateAgentPrompts } from '../engine/agent-prompt-generator.js';
import { readFile } from 'node:fs/promises';
import { stripFrontmatter } from '../engine/frontmatter-parser.js';
import { compactJson } from './output-formatter.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function text(content) {
    return { content: [{ type: 'text', text: compactJson(content) }] };
}
function err(message) {
    return { content: [{ type: 'text', text: message }], isError: true };
}
/** Extract acceptance criteria from a spec.md file. */
async function extractCriteria(specPath) {
    try {
        const rawContent = await readFile(specPath, 'utf-8');
        const content = stripFrontmatter(rawContent);
        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;
    }
    catch {
        return [];
    }
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleGenerateTeammatePrompt(params) {
    const { projectId, specId, teammateName, assignedFiles, role } = params;
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return err(`Spec '${specId}' not found in project '${projectId}'. Check the spec ID.`);
    }
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    const constitution = await knowledgeStore.getConstitution(projectId);
    const criteria = await extractCriteria(spec.specPath);
    const prompt = buildTeammatePrompt({
        projectLanguage: knowledge?.language ?? 'unknown',
        projectFramework: knowledge?.framework ?? null,
        architecture: knowledge?.architecture.primary ?? 'unknown',
        conventions: knowledge?.conventions ?? {},
        specDetails: { id: spec.id, title: spec.title, criteria },
        ownedFiles: assignedFiles ?? [],
        forbiddenFiles: [],
        qualityRules: constitution?.principles.map((p) => p.principle) ?? [],
        testingRequirements: [
            `Test runner: ${knowledge?.testCommand ?? 'pnpm test'}`,
            'Coverage must be >= 95%',
            `Type check: ${knowledge?.buildCommand ?? 'pnpm typecheck'}`,
        ],
        gitConventions: [
            'Use conventional commits (feat:, fix:, docs:, etc.)',
            `Branch naming: feat/${spec.id}-short-name`,
            'Never commit directly to main or develop',
        ],
        validationCommands: [
            knowledge?.buildCommand ?? 'pnpm typecheck',
            knowledge?.lintCommand ?? 'pnpm lint',
            knowledge?.testCommand ?? 'pnpm test',
        ],
    });
    return text({ teammateName, role, specId, prompt });
}
// ---------------------------------------------------------------------------
// Layer-based agent prompt handler
// ---------------------------------------------------------------------------
/**
 * Generate agent prompts based on detected architecture layers.
 * When `layer` is omitted, generates prompts for all detected layers.
 */
export async function handleGenerateLayerPrompts(params) {
    const { projectId, layer } = params;
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge) {
        return err(`No project knowledge found for '${projectId}'. Run init_project or scan_project first.`);
    }
    const prompts = generateAgentPrompts(knowledge, layer);
    if (prompts.length === 0) {
        const hint = layer
            ? `Layer '${layer}' was not detected in project '${projectId}'.`
            : `No layers detected in project '${projectId}'.`;
        return err(`${hint} Run scan_project to detect architecture layers first.`);
    }
    return text({
        projectId,
        generatedCount: prompts.length,
        agents: prompts.map((p) => ({
            name: p.name,
            layer: p.layer,
            recommendedModel: p.recommendedModel,
            ownedPaths: p.ownedPaths,
            prompt: p.prompt,
        })),
    });
}
//# sourceMappingURL=generate-teammate-prompt.js.map