// engine/ai-integration/agents-md/generator.ts — Universal AGENTS.md generator (SPEC-269)
import { writeFileSync, readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { assertEnglishOnlyArtifactText } from '../../spec-language/english-only.js';
const PLANU_SECTION_START = '<!-- planu-sdd:start -->';
const PLANU_SECTION_END = '<!-- planu-sdd:end -->';
function buildActiveSpecBlock(activeSpecId, activeSpecTitle) {
    if (activeSpecId !== undefined && activeSpecTitle !== undefined) {
        return [
            '### Active Spec',
            '',
            `**${activeSpecId}**: ${activeSpecTitle}`,
            '',
            'Implement this spec next. Follow all criteria exactly.',
        ].join('\n');
    }
    return [
        '### Active Spec',
        '',
        'No active spec. Use `create_spec` to define the next feature before writing code.',
    ].join('\n');
}
function buildApprovedQueueBlock(approvedSpecs) {
    if (approvedSpecs.length === 0) {
        return '';
    }
    const lines = ['### Approved Queue', ''];
    for (const spec of approvedSpecs) {
        lines.push(`- **${spec.id}**: ${spec.title}`);
    }
    lines.push('', 'Implement specs in order. Do not skip ahead.');
    return lines.join('\n');
}
function buildWorkflowBlock() {
    return [
        '### SDD Workflow (MANDATORY)',
        '',
        '**Spec before code — no exceptions.**',
        '',
        '1. Describe the feature → Planu creates a spec via `create_spec`',
        '2. Review + approve the spec (`update_status` → approved)',
        '3. Implement on a `feat/SPEC-XXX-*` branch',
        '4. Validate after implementation: `validate`',
        '5. Merge and promote to done: `update_status` → done',
    ].join('\n');
}
function buildToolsBlock() {
    return [
        '### Planu MCP Tools',
        '',
        'Compatible with 25+ AI tools (Codex, Copilot, Cursor, Windsurf, Kiro, Cline, Continue.dev, Aider).',
        '',
        '| Tool | Purpose |',
        '|------|---------|',
        '| `create_spec` | Create a new spec for a feature |',
        '| `list_specs` | List all specs and their status |',
        '| `update_status` | Move spec through workflow stages |',
        '| `validate` | Check implementation against spec criteria |',
        '| `challenge_spec` | Stress-test spec for gaps before implementation |',
        '| `check_readiness` | Verify spec has enough detail to implement |',
    ].join('\n');
}
function buildBranchBlock(branchConvention) {
    return [
        '### Branch Naming',
        '',
        '```',
        branchConvention,
        'fix/SPEC-XXX-bug-description      # bug fix spec',
        '```',
        '',
        '- Always branch from `develop`',
        '- Branch name must include the spec ID',
        '- Never commit directly to `develop` or `main`',
    ].join('\n');
}
function buildArchitectureBlock(options) {
    const lines = ['### Architecture Rules'];
    if (options.architectureStyle !== undefined && options.architectureStyle.length > 0) {
        lines.push('', `**Style**: ${options.architectureStyle}`);
    }
    if (options.stack.length > 0) {
        lines.push('', `**Stack**: ${options.stack.join(', ')}`);
    }
    lines.push('', '- `types/` → no imports from other layers', '- `engine/` → imports only from `types/`', '- `storage/` → imports only from `types/`', '- `tools/` → imports from `engine/` + `storage/` + `types/`', '- Cross-layer violations → ESLint error', '- Read the codebase before writing new files');
    return lines.join('\n');
}
function buildSddSection(options) {
    const branchConvention = options.branchConvention ?? 'feat/SPEC-XXX-short-description';
    const activeSpecBlock = buildActiveSpecBlock(options.activeSpecId, options.activeSpecTitle);
    const approvedQueueBlock = buildApprovedQueueBlock(options.approvedSpecs);
    const workflowBlock = buildWorkflowBlock();
    const toolsBlock = buildToolsBlock();
    const branchBlock = buildBranchBlock(branchConvention);
    const architectureBlock = buildArchitectureBlock(options);
    const parts = [
        PLANU_SECTION_START,
        '',
        `## Planu SDD — ${options.projectName}`,
        '',
        workflowBlock,
        '',
        activeSpecBlock,
    ];
    if (approvedQueueBlock.length > 0) {
        parts.push('', approvedQueueBlock);
    }
    parts.push('', toolsBlock, '', branchBlock, '', architectureBlock, '', PLANU_SECTION_END);
    const content = parts.join('\n');
    assertEnglishOnlyArtifactText(content, 'agent');
    return content;
}
/** Generates the full universal AGENTS.md content for a project using Planu SDD. */
export function generateUniversalAgentsMd(options) {
    return buildSddSection(options);
}
/**
 * Writes AGENTS.md to projectPath.
 * Idempotent: replaces the planu-sdd section if it already exists,
 * appends if the file exists without the section,
 * or creates the file from scratch.
 */
export function writeUniversalAgentsMd(projectPath, options) {
    const filePath = join(projectPath, 'AGENTS.md');
    const newSection = buildSddSection(options);
    if (!existsSync(filePath)) {
        writeFileSync(filePath, newSection + '\n', 'utf8');
        return;
    }
    const existing = readFileSync(filePath, 'utf8');
    const startIdx = existing.indexOf(PLANU_SECTION_START);
    const endIdx = existing.indexOf(PLANU_SECTION_END);
    if (startIdx === -1 || endIdx === -1) {
        const separator = existing.endsWith('\n') ? '' : '\n';
        writeFileSync(filePath, existing + separator + newSection + '\n', 'utf8');
        return;
    }
    const before = existing.slice(0, startIdx);
    const after = existing.slice(endIdx + PLANU_SECTION_END.length);
    writeFileSync(filePath, before + newSection + after, 'utf8');
}
//# sourceMappingURL=generator.js.map