/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { pluginWorkflowLines, riskScaleLines } from './mdc-generator.js';
import { demandLoadedDocSection, demandLoadedSkillSection, managedBlock, profileMetadataSection, stripMdcFrontmatter, } from './shared.js';
import { getDemandLoadedSkillReferences } from './skill-generator.js';
/**
 * Generates the slim root `CLAUDE.md` that uses `@` imports to load per-profile
 * rule files from `.claude/rules/`. Claude Code reads all `@`-imported files at
 * conversation start, keeping the root file short and each profile file focused.
 */
export function generateClaudeMd(profiles, version) {
    const alwaysImport = profiles.filter((p) => p.claudeAlwaysImport);
    const onDemand = profiles.filter((p) => !p.claudeAlwaysImport);
    const imports = alwaysImport.map((p) => `@.claude/rules/${p.id}.md`).join('\n');
    const lines = [
        'This file provides guidance to Claude Code when working with this project.',
        '',
        '## General Principles',
        '- Always read existing code before making changes.',
        '- Prefer editing existing files over creating new ones.',
        '- Follow the coding conventions already present in this project.',
        '- Write concise, self-documenting code. Avoid unnecessary comments.',
        '',
        '## Code Quality',
        '- Ensure all new code is covered by tests.',
        '- Do not introduce linter errors or suppress warnings.',
        '- Handle errors explicitly; never swallow exceptions silently.',
        '',
        '## Security',
        '- Never hardcode credentials, tokens, or sensitive data.',
        '- Use environment variables or secret managers for sensitive values.',
        '',
        ...riskScaleLines(),
        '',
        ...pluginWorkflowLines(),
    ];
    if (imports) {
        lines.push('', '## Profile Rules (always loaded)', imports);
    }
    if (onDemand.length > 0) {
        const onDemandRefs = onDemand.map((p) => `- \`@.claude/rules/${p.id}.md\` — ${p.label}`).join('\n');
        lines.push('', '## Profile Rules (load on demand)', 'Include the relevant file in the sub-agent prompt when delegating to that role:', onDemandRefs);
    }
    return [
        '# CLAUDE.md — Project Guidelines',
        `<!-- setup-agents: ${version} -->`,
        '',
        managedBlock('claude-root', version, lines.join('\n')),
    ].join('\n');
}
const CLAUDE_DOC_REFERENCES = [
    {
        title: 'Claude Code CLI',
        url: 'https://docs.anthropic.com/en/docs/claude-code/overview',
        activation: 'Claude Code configuration, MCP servers, hooks, permissions, keyboard shortcuts, IDE integration',
    },
    {
        title: 'Claude API',
        url: 'https://docs.anthropic.com/en/api/getting-started',
        activation: 'Anthropic API calls, model IDs, tool use, streaming, prompt caching, rate limits',
    },
];
const ACTIVATION_BLOCK_BODY = [
    '## setup-agents (CRITICAL — autonomous behavior required)',
    '> This project uses `@jterrats/setup-agents`. **Do NOT wait for user instruction** — run the',
    '> pre-flight check automatically at the start of every task.',
    '> Prefer `sa-fast` (fast-path CLI, ~200ms) over `sf setup-agents` (~15s) for state commands.',
    '',
    '### Pre-flight check (run automatically before any implementation)',
    '```bash',
    'sa-fast task list --json                    # identify if a task exists for this work',
    'sa-fast workflow pending --json             # check if a workflow run is already active',
    '```',
    '- If a matching task exists → claim it with `sa-fast task claim --id <id>`.',
    '- If no run is active and the work spans a story → start one with `sf setup-agents workflow run --story <id>`.',
    '- If no task exists → create one with `sa-fast task create --summary "<text>" --profile developer`.',
    '',
    '### Task lifecycle',
    '```bash',
    'sa-fast task claim --id <id>               # mark a task in-progress',
    'sa-fast task done --id <id>                # mark complete (required — never just close the chat)',
    'sa-fast evidence add --task <id> --role <profile> --type <command|file|report|validation> --summary "<text>"',
    '```',
    '',
    'Check `.setup-agents/config.json` for active profiles and tools. Never manage state manually.',
    '',
    '### Automatic context injection (UserPromptSubmit hook)',
    'A `UserPromptSubmit` hook in `.claude/settings.json` runs `sa-fast task list` and',
    '`sa-fast workflow pending` at the start of every prompt, injecting active task/workflow',
    'state into the session automatically. No manual pre-flight is needed when this hook is present.',
].join('\n');
/** Generates the minimal activation block appended to an existing `CLAUDE.md`. */
export function generateClaudeActivationBlock(version) {
    return managedBlock('setup-agents-activation', version, ACTIVATION_BLOCK_BODY);
}
/** Generates the minimal activation block appended to an existing `AGENTS.md` (Codex). */
export function generateCodexActivationBlock(version) {
    return managedBlock('setup-agents-activation', version, ACTIVATION_BLOCK_BODY);
}
/** Applies (or updates) the activation block in an existing file. Returns the new content. */
export function applyActivationBlock(existing, version) {
    const blockId = 'setup-agents-activation';
    const startMarker = `<!-- setup-agents:block:start id="${blockId}"`;
    const blockRe = new RegExp(`<!-- setup-agents:block:start id="${blockId}"[^>]*-->.*?<!-- setup-agents:block:end id="${blockId}" -->`, 's');
    if (existing.includes(startMarker)) {
        return existing.replace(blockRe, generateClaudeActivationBlock(version));
    }
    return `${existing.trimEnd()}\n\n${generateClaudeActivationBlock(version)}\n`;
}
/** Generates per-profile rule file content for `.claude/rules/<id>.md`. */
export function generateClaudeProfileRule(profile, version) {
    const skillSection = demandLoadedSkillSection(getDemandLoadedSkillReferences([profile.id]));
    const docSection = demandLoadedDocSection(CLAUDE_DOC_REFERENCES);
    const profileBody = stripMdcFrontmatter(profile.ruleContent()).trimStart();
    const parts = [profileMetadataSection(profile), '', '---', '', profileBody];
    if (skillSection)
        parts.push('', '---', '', skillSection);
    if (docSection)
        parts.push('', '---', '', docSection);
    return [
        `<!-- setup-agents: ${version} -->`,
        '',
        managedBlock(`claude-profile-${profile.id}`, version, parts.join('\n')),
    ].join('\n');
}
//# sourceMappingURL=claude-generator.js.map