/*
 * 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 root `AGENTS.md` for OpenAI Codex CLI.
 * Per-profile rules live in `.codex/<id>.md` and are referenced via an
 * explicit `read` instruction.
 */
export function generateAgentsMd(profiles, version, opts) {
    const alwaysImport = profiles.filter((p) => p.claudeAlwaysImport);
    const onDemand = profiles.filter((p) => !p.claudeAlwaysImport);
    const profileRefs = alwaysImport.map((p) => `- \`.codex/${p.id}.md\` — ${p.label} rules`).join('\n');
    const lines = [
        '## 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 (profileRefs) {
        lines.push('', '## Profile Rules (always loaded)', 'Read the following files for role-specific standards before generating code:', profileRefs);
    }
    if (onDemand.length > 0) {
        const onDemandRefs = onDemand.map((p) => `- \`.codex/${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);
    }
    if (opts?.isSalesforceProject) {
        const apexProfiles = profiles.filter((p) => ['developer', 'ta', 'qa', 'devops'].includes(p.id));
        if (apexProfiles.length > 0) {
            lines.push('', '## Salesforce Source Rules', '', '### Apex', '- Default: `with sharing`. Exception: `@RestResource` classes → `without sharing`.', '- No SOQL or DML inside loops.', '- One trigger per object. Zero logic in triggers — delegate to trigger handler.', '- Always bulkify: handle 1 to N records.', '', '### LWC', '- Prioritize SLDS Styling Hooks over custom CSS.', '- Use LDS 2 and Lightning Data Service whenever possible.', '- User feedback: Toasts with Custom Labels. Never hardcode strings.', '', '### Testing', '- Exactly one Assert per test method using the modern `Assert` class.', '- Use `@TestSetup` for shared test data.', '- Target 90% code coverage.');
        }
    }
    return [
        '# Agent Guidelines',
        `<!-- setup-agents: ${version} -->`,
        '',
        managedBlock('codex-root', version, lines.join('\n')),
    ].join('\n');
}
const CODEX_DOC_REFERENCES = [
    {
        title: 'OpenAI Codex CLI',
        url: 'https://github.com/openai/codex',
        activation: 'Codex CLI configuration, AGENTS.md conventions, sandbox policy, approval modes',
    },
    {
        title: 'OpenAI API',
        url: 'https://platform.openai.com/docs/overview',
        activation: 'OpenAI API calls, model IDs, tool use, function calling, rate limits, responses API',
    },
];
/** Generates per-profile rule file content for `.codex/<id>.md`. */
export function generateCodexProfileRule(profile, version) {
    const skillSection = demandLoadedSkillSection(getDemandLoadedSkillReferences([profile.id]));
    const docSection = demandLoadedDocSection(CODEX_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(`codex-profile-${profile.id}`, version, parts.join('\n')),
    ].join('\n');
}
//# sourceMappingURL=codex-generator.js.map