/*
 * 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.
 */
/**
 * Generates Cursor Skill files (`.cursor/skills/<name>/SKILL.md`) and portable
 * skill content for other AI tools (Claude Code, Codex, Copilot, Agentforce).
 *
 * Each "generate*Skill()" function returns a `Record<relativePath, content>` map
 * for Cursor's native SKILL.md format (with YAML frontmatter + assets).
 *
 * The portable API (`getPortableSkillSections`, `getSharedSkillAssets`)
 * provides tool-agnostic content that each tool's generator can embed.
 */
import { profilesForCapability } from '../profiles/index.js';
import { backlogSyncSkillMd } from './backlog-sync-content.js';
import { codeAnalyzerSkillMd } from './code-analyzer-content.js';
import { deploySkillMd } from './deploy-content.js';
import { diagramExportSkillMd, exportDiagramScript } from './diagram-export-content.js';
import { diagramThemeDefaultsJson } from './diagram-theme-defaults-content.js';
import { elementsSyncSkillMd, pushToElementsScript } from './elements-sync-content.js';
import { generateGeneratedPrompts, promptRegistrySkillMd } from './generated-prompts-generator.js';
import { lucidShapeCatalogMd } from './lucid-shape-catalog-content.js';
import { oclifPluginSkillMd } from './oclif-plugin-content.js';
import { projectKnowledgeBootstrapSkillMd } from './project-knowledge-bootstrap-content.js';
import { qaEvidencePackSkillMd } from './qa-evidence-pack-content.js';
import { stripMdcFrontmatter } from './shared.js';
import { mermaidPdfCss, renderPdfScript, storyMappingSkillMd } from './story-mapping-content.js';
import { transcribeScript, transcriptionSkillMd } from './transcription-content.js';
import { workflowEstimateSkillMd } from './workflow-estimate-content.js';
export function profilesWithCapability(cap) {
    return new Set(profilesForCapability(cap));
}
export const STORY_MAP_PROFILES = profilesWithCapability('story-mapping');
export const DEPLOY_PROFILES = profilesWithCapability('deploy');
export const CODE_ANALYZER_PROFILES = profilesWithCapability('code-analysis');
export const BACKLOG_SYNC_PROFILES = profilesWithCapability('backlog-sync');
export const ELEMENTS_SYNC_PROFILES = profilesWithCapability('elements-sync');
export const DOC_SYNC_PROFILES = profilesWithCapability('doc-sync');
export const DECLARE_POINTS_PROFILES = profilesWithCapability('declare-points');
export const PROMPT_REGISTRY_PROFILES = profilesWithCapability('prompt-registry');
export const QA_EVIDENCE_PROFILES = profilesWithCapability('qa-evidence');
export const OCLIF_PLUGIN_PROFILES = profilesWithCapability('oclif-plugin');
export const PROJECT_KNOWLEDGE_BOOTSTRAP_PROFILES = profilesWithCapability('project-knowledge-bootstrap');
export const TRANSCRIPTION_PROFILES = profilesWithCapability('transcription');
/**
 * Returns portable skill sections (plain markdown, no YAML frontmatter)
 * for the given profile IDs. Each tool's generator appends these to its config.
 */
export function getPortableSkillSections(profileIds) {
    const ids = new Set(profileIds);
    const sections = [];
    if ([...ids].some((id) => STORY_MAP_PROFILES.has(id))) {
        sections.push({
            title: 'Story Mapping',
            body: stripMdcFrontmatter(storyMappingSkillMd()).trim(),
        });
        sections.push({
            title: 'Diagram Export',
            body: stripMdcFrontmatter(diagramExportSkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => DEPLOY_PROFILES.has(id))) {
        sections.push({
            title: 'Salesforce Deploy & Validate',
            body: stripMdcFrontmatter(deploySkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => CODE_ANALYZER_PROFILES.has(id))) {
        sections.push({
            title: 'Salesforce Code Analyzer',
            body: stripMdcFrontmatter(codeAnalyzerSkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => QA_EVIDENCE_PROFILES.has(id))) {
        sections.push({
            title: 'QA Evidence Pack',
            body: stripMdcFrontmatter(qaEvidencePackSkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => BACKLOG_SYNC_PROFILES.has(id))) {
        sections.push({
            title: 'Backlog Sync',
            body: stripMdcFrontmatter(backlogSyncSkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => ELEMENTS_SYNC_PROFILES.has(id))) {
        sections.push({
            title: 'Elements Sync',
            body: stripMdcFrontmatter(elementsSyncSkillMd()).trim(),
        });
    }
    if ([...ids].some((id) => OCLIF_PLUGIN_PROFILES.has(id))) {
        sections.push({
            title: 'oclif Plugin Development',
            body: stripMdcFrontmatter(oclifPluginSkillMd()).trim(),
        });
    }
    return sections;
}
export function getDemandLoadedSkillReferences(profileIds) {
    const ids = new Set(profileIds);
    const references = [];
    if ([...ids].some((id) => STORY_MAP_PROFILES.has(id))) {
        references.push({
            title: 'Story Mapping',
            path: '.setup-agents/skills/story-mapping/SKILL.md',
            activation: 'story maps, epic breakdowns, release planning maps, backlog visualization',
        });
        references.push({
            title: 'Diagram Export',
            path: '.setup-agents/skills/diagram-export/SKILL.md',
            activation: 'Mermaid, architecture, sequence, workflow, Lucidchart, draw.io, SVG, or PDF diagram export',
        });
    }
    if ([...ids].some((id) => DEPLOY_PROFILES.has(id))) {
        references.push({
            title: 'Salesforce Deploy & Validate',
            path: '.setup-agents/skills/sf-deploy/SKILL.md',
            activation: 'Salesforce deploy, validate, quick deploy, package, or deployment troubleshooting',
        });
    }
    if ([...ids].some((id) => CODE_ANALYZER_PROFILES.has(id))) {
        references.push({
            title: 'Salesforce Code Analyzer',
            path: '.setup-agents/skills/sf-code-analyzer/SKILL.md',
            activation: 'static analysis, Salesforce Code Analyzer, PMD, ESLint, rulesets, or quality gate evidence',
        });
    }
    if ([...ids].some((id) => QA_EVIDENCE_PROFILES.has(id))) {
        references.push({
            title: 'QA Evidence Pack',
            path: '.setup-agents/skills/qa-evidence-pack/SKILL.md',
            activation: 'QA evidence, test evidence, acceptance criteria coverage, Playwright, screenshots, traces, videos, CLI output, API contracts, integration side effects, or release evidence',
        });
    }
    if ([...ids].some((id) => BACKLOG_SYNC_PROFILES.has(id))) {
        references.push({
            title: 'Backlog Sync',
            path: '.setup-agents/skills/backlog-sync/SKILL.md',
            activation: 'GitHub issues, epics, story refinement, acceptance criteria, or backlog synchronization',
        });
    }
    if ([...ids].some((id) => ELEMENTS_SYNC_PROFILES.has(id))) {
        references.push({
            title: 'Elements Sync',
            path: '.setup-agents/skills/elements-sync/SKILL.md',
            activation: 'Elements.cloud requirements, stories, process maps, or metadata traceability',
        });
    }
    if ([...ids].some((id) => OCLIF_PLUGIN_PROFILES.has(id))) {
        references.push({
            title: 'oclif Plugin Development',
            path: '.setup-agents/skills/oclif-plugin/SKILL.md',
            activation: 'oclif command, sf plugin, CLI flag, hook, manifest, sf-plugins-core, SfCommand, Messages, schema generate, command snapshot, wireit, plugin link',
        });
    }
    if ([...ids].some((id) => DECLARE_POINTS_PROFILES.has(id))) {
        references.push({
            title: 'Declare Story Points',
            path: '.setup-agents/playbooks/declare-story-points.md',
            activation: 'closing a phase, task completion, story-point declaration, effort recording, phase wrap-up',
        });
    }
    if ([...ids].some((id) => PROJECT_KNOWLEDGE_BOOTSTRAP_PROFILES.has(id))) {
        references.push({
            title: 'Project Knowledge Bootstrap',
            path: '.setup-agents/skills/project-knowledge-bootstrap/SKILL.md',
            activation: 'project-knowledge.md has empty sections, first architect task, codebase onboarding, naming convention detection, force-app scan',
        });
    }
    if ([...ids].some((id) => TRANSCRIPTION_PROFILES.has(id))) {
        references.push({
            title: 'Transcription Evidence',
            path: '.setup-agents/skills/transcription-evidence/SKILL.md',
            activation: 'transcribe audio, transcribe video, whisper, speech-to-text, meeting recording, transcript evidence',
        });
    }
    references.push({
        title: 'Command Permissions',
        path: '.setup-agents/permissions.md',
        activation: 'before executing shell commands, validating command safety, checking allow/deny lists',
    });
    return references;
}
/**
 * Returns shared filesystem assets (scripts, CSS) that are tool-agnostic.
 * Keys are relative paths under `.setup-agents/skills/`.
 */
export function getSharedSkillAssets(profileIds) {
    const ids = new Set(profileIds);
    const assets = {};
    if ([...ids].some((id) => STORY_MAP_PROFILES.has(id))) {
        assets['story-mapping/scripts/render-pdf.sh'] = renderPdfScript();
        assets['story-mapping/assets/mermaid-pdf.css'] = mermaidPdfCss();
        assets['diagram-export/scripts/export-diagram.sh'] = exportDiagramScript();
    }
    if ([...ids].some((id) => ELEMENTS_SYNC_PROFILES.has(id))) {
        assets['elements-sync/scripts/push-to-elements.sh'] = pushToElementsScript();
    }
    if ([...ids].some((id) => TRANSCRIPTION_PROFILES.has(id))) {
        assets['transcription-evidence/scripts/transcribe.sh'] = transcribeScript();
    }
    return assets;
}
export function getDemandLoadedSkillFiles(profileIds) {
    const ids = new Set(profileIds);
    const files = {};
    const addSkill = (dirName, skillFiles) => {
        for (const [relativePath, content] of Object.entries(skillFiles)) {
            files[`${dirName}/${relativePath}`] = content;
        }
    };
    if ([...ids].some((id) => STORY_MAP_PROFILES.has(id))) {
        addSkill('story-mapping', generateStoryMappingSkill());
        addSkill('diagram-export', generateDiagramExportSkill());
    }
    if ([...ids].some((id) => DEPLOY_PROFILES.has(id))) {
        addSkill('sf-deploy', generateDeploySkill());
    }
    if ([...ids].some((id) => CODE_ANALYZER_PROFILES.has(id))) {
        addSkill('sf-code-analyzer', generateCodeAnalyzerSkill());
    }
    if ([...ids].some((id) => QA_EVIDENCE_PROFILES.has(id))) {
        addSkill('qa-evidence-pack', generateQaEvidencePackSkill());
    }
    if ([...ids].some((id) => BACKLOG_SYNC_PROFILES.has(id))) {
        addSkill('backlog-sync', generateBacklogSyncSkill());
    }
    if ([...ids].some((id) => ELEMENTS_SYNC_PROFILES.has(id))) {
        addSkill('elements-sync', generateElementsSyncSkill());
    }
    if ([...ids].some((id) => OCLIF_PLUGIN_PROFILES.has(id))) {
        addSkill('oclif-plugin', generateOclifPluginSkill());
    }
    if ([...ids].some((id) => DECLARE_POINTS_PROFILES.has(id))) {
        addSkill('workflow-estimate', generateWorkflowEstimateSkill());
    }
    if ([...ids].some((id) => PROJECT_KNOWLEDGE_BOOTSTRAP_PROFILES.has(id))) {
        addSkill('project-knowledge-bootstrap', generateProjectKnowledgeBootstrapSkill());
    }
    if ([...ids].some((id) => TRANSCRIPTION_PROFILES.has(id))) {
        addSkill('transcription-evidence', generateTranscriptionEvidenceSkill());
    }
    return files;
}
/**
 * Returns reference files keyed by relative path under `.setup-agents/references/`.
 * These provide tool-agnostic knowledge (shape catalogs, themes) for diagram generation.
 */
export function getReferenceFiles(profileIds) {
    const ids = new Set(profileIds);
    const files = {};
    if ([...ids].some((id) => STORY_MAP_PROFILES.has(id))) {
        files['lucid-shape-catalog.md'] = lucidShapeCatalogMd();
        files['diagram-theme.defaults.json'] = diagramThemeDefaultsJson();
    }
    return files;
}
/**
 * Returns `.generated-prompts/` register files keyed by filename.
 * These are written to `.generated-prompts/` at the repo root (not under `.setup-agents/`).
 * Only called for Salesforce projects.
 */
export function getPromptRegistryFiles(profileIds, version) {
    const ids = new Set(profileIds);
    if (![...ids].some((id) => PROMPT_REGISTRY_PROFILES.has(id)))
        return {};
    return generateGeneratedPrompts(version, profileIds);
}
// ─── Cursor-native Skill (SKILL.md + assets) ──────────────────────────────
export function generatePromptRegistrySkill() {
    return { 'SKILL.md': promptRegistrySkillMd() };
}
export function generateQaEvidencePackSkill() {
    return { 'SKILL.md': qaEvidencePackSkillMd() };
}
export function generateStoryMappingSkill() {
    return {
        'SKILL.md': storyMappingSkillMd(),
        'scripts/render-pdf.sh': renderPdfScript(),
        'assets/mermaid-pdf.css': mermaidPdfCss(),
    };
}
// ─── Diagram Export Skill ──────────────────────────────────────────────────
export function generateDiagramExportSkill() {
    return {
        'SKILL.md': diagramExportSkillMd(),
        'scripts/export-diagram.sh': exportDiagramScript(),
    };
}
// ─── Deploy/Validate Skill ─────────────────────────────────────────────────
export function generateDeploySkill() {
    return {
        'SKILL.md': deploySkillMd(),
    };
}
// ─── Code Analyzer Skill ───────────────────────────────────────────────────
export function generateCodeAnalyzerSkill() {
    return {
        'SKILL.md': codeAnalyzerSkillMd(),
    };
}
export function generateBacklogSyncSkill() {
    return {
        'SKILL.md': backlogSyncSkillMd(),
    };
}
export function generateElementsSyncSkill() {
    return {
        'SKILL.md': elementsSyncSkillMd(),
        'scripts/push-to-elements.sh': pushToElementsScript(),
    };
}
export function generateOclifPluginSkill() {
    return { 'SKILL.md': oclifPluginSkillMd() };
}
export function generateWorkflowEstimateSkill() {
    return { 'SKILL.md': workflowEstimateSkillMd() };
}
export function generateProjectKnowledgeBootstrapSkill() {
    return { 'SKILL.md': projectKnowledgeBootstrapSkillMd() };
}
export function generateTranscriptionEvidenceSkill(version = '1.0.0') {
    return {
        'SKILL.md': transcriptionSkillMd(version),
        'scripts/transcribe.sh': transcribeScript(),
    };
}
/** Profile-specific doc checklist entries used by generateDocSyncSkill. */
const DOC_CHECKLIST_BY_PROFILE = [
    {
        ids: ['ta', 'architect'],
        heading: '### Architect',
        items: [
            "- [ ] `docs/adr/` — create or update ADR for any decision record with `kind: 'decision'`",
            '- [ ] `docs/architecture.md` — update integration points section if new integrations were added',
            '- [ ] `docs/diagrams/` — reference new Mermaid diagrams produced in this task',
            '- [ ] `docs/reviews/` — append architecture review findings if a review record exists',
        ],
    },
    {
        ids: ['developer'],
        heading: '### Developer',
        items: [
            '- [ ] `CHANGELOG.md` — append entry under [Unreleased] for new commands, flags, or breaking changes',
            '- [ ] `docs/commands.html` or equivalent — update if a new command or flag was added',
            '- [ ] `docs/api/` — update API reference if public interfaces changed',
            '- [ ] Note new environment variables or dependencies in `README.md`',
        ],
    },
    {
        ids: ['qa'],
        heading: '### QA',
        items: [
            '- [ ] `docs/testing/` — append test coverage delta and any new test patterns introduced',
            '- [ ] `docs/testing/known-failures.md` — document any known failures or flaky tests discovered',
            '- [ ] `docs/testing/regression-notes.md` — note regressions caught and how they were resolved',
        ],
    },
    {
        ids: ['devops'],
        heading: '### DevOps',
        items: [
            '- [ ] `docs/deployment/runbook.md` — update deployment steps if pipeline changed',
            '- [ ] `docs/deployment/env-vars.md` — document new environment variables introduced',
            '- [ ] `docs/deployment/cicd.md` — update CI/CD workflow descriptions if changed',
        ],
    },
];
/** Build profile-specific doc checklist lines for the given profile IDs. */
function generateProfileDocChecklist(activeIds) {
    const lines = [];
    for (const entry of DOC_CHECKLIST_BY_PROFILE) {
        if (!entry.ids.some((id) => activeIds.has(id)))
            continue;
        lines.push('', entry.heading, ...entry.items);
    }
    return lines;
}
export function generateDocSyncSkill(profiles, version) {
    const ids = new Set(profiles.map((p) => p.id));
    const lines = [
        '---',
        'name: doc-sync',
        'description: >-',
        '  Update project documentation after task completion. USE FOR: sync docs, update ADR,',
        '  update changelog, post-task doc update, sa-fast task done, doc sync.',
        `pluginVersion: "${version}"`,
        '---',
        '',
        '# doc-sync Skill',
        '',
        'Run this skill after every `sa-fast task done` (or `sf setup-agents task done`) to keep project docs in sync with actual implementation.',
        '',
        '## Trigger',
        'After any `sa-fast task done` / `sf setup-agents task done` / `orchestra task done` call completes successfully.',
        '',
        '## Protocol',
        '',
        '1. Run `sf setup-agents evidence list --task <id> --json` and `sf setup-agents decision list --task <id> --json`.',
        '2. Identify which doc files are affected based on the task role and evidence type (see checklist below).',
        '3. Open the relevant file. Find or create the section for this task using managed-block markers:',
        '   `<!-- setup-agents:block:start id="<task-id>" -->`',
        '   `<!-- setup-agents:block:end id="<task-id>" -->`',
        "4. Update the content between markers. If markers don't exist, append a new section at the end of the file.",
        '5. Never delete content outside managed blocks.',
        '',
        '## Doc Target Checklist by Profile',
        ...generateProfileDocChecklist(ids),
        '',
        '## Rules',
        '- Keep each update under 20 lines per managed block — link to ADRs for detail.',
        '- Use `should` not `must` — missing docs do not block task completion.',
        '- Do not modify content outside managed blocks.',
    ];
    return lines.join('\n');
}
//# sourceMappingURL=skill-generator.js.map