/*
 * 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.
 */
/**
 * Prompt Registry skill — generates `.generated-prompts/` register files and
 * the SKILL.md that teaches the agent how to read/write them.
 *
 * Files are profile-scoped: each profile only gets the register files relevant
 * to the artifacts it generates.
 */
// ─── Profile → register files map ─────────────────────────────────────────
/** All register files a given profile needs in `.generated-prompts/`. */
const PROFILE_FILES = {
    developer: ['apex.md', 'lwc.md', 'flows.md', 'triggers.md', 'visualforce.md', 'aura.md', 'metadata.md'],
    ta: ['apex.md', 'flows.md', 'metadata.md', 'diagrams.md', 'docs.md'],
    architect: ['apex.md', 'flows.md', 'metadata.md', 'diagrams.md', 'docs.md'],
    admin: ['flows.md', 'metadata.md'],
    ba: ['flows.md', 'diagrams.md', 'docs.md'],
    ux: ['lwc.md', 'diagrams.md', 'docs.md'],
    pm: ['diagrams.md', 'docs.md'],
    devops: ['cicd.md', 'docs.md'],
    mulesoft: ['cicd.md', 'docs.md'],
    qa: ['tests.md'],
    omnistudio: ['omnistudio.md', 'metadata.md'],
    crma: ['docs.md'],
    data360: ['docs.md'],
    security: ['metadata.md', 'docs.md'],
};
/** Returns the union of register file names needed for a set of profile IDs. */
export function promptRegistryFiles(profileIds) {
    const files = new Set();
    for (const id of profileIds) {
        for (const file of PROFILE_FILES[id] ?? []) {
            files.add(file);
        }
    }
    return [...files].sort();
}
// ─── SKILL.md ──────────────────────────────────────────────────────────────
export function promptRegistrySkillMd() {
    return `---
name: prompt-registry
description: >-
  Maintain the .generated-prompts/ register: read before creating any artifact
  to infer project conventions, write/update after creation. Keeps the latest
  prompt that produced each component so the team can trace every generated
  artifact back to its origin. USE FOR: generated prompts, prompt history,
  prompt register, artifact traceability, prompt registry, generated apex,
  generated lwc, generated flow, generated component, vibe coding history,
  prompt persistence, ai prompt log. Active for Developer, Architect, Admin,
  BA, UX, PM, DevOps, MuleSoft, QA, OmniStudio, CRMA, Data Cloud, Security profiles.
---

# Prompt Registry

## Overview

\`.generated-prompts/\` is a commit-tracked directory at the repo root.
Each file registers the AI prompts that created or substantially changed
artifacts of a given type. One entry per component. Latest prompt only.
The git history holds the version trail.

## Before creating any artifact (MANDATORY)

1. Check if \`.generated-prompts/<type>.md\` exists.
2. If it exists, read the **entire file** before generating the artifact.
3. Use existing entries to infer:
   - Naming conventions in use
   - Data layer strategy (dynamic queries utility, selector layer, inline SOQL, etc.)
   - Patterns already established (trigger handler style, flow sub-flow depth, etc.)
   - Sharing model decisions
   - Any project-specific constraints recorded in prior prompts
4. Generate the new artifact **consistent with those conventions**.

## After creating or substantially changing an artifact (MANDATORY)

1. Open the corresponding \`.generated-prompts/<type>.md\`.
2. Search for an existing \`## <ComponentName>\` heading.
3. **No existing entry** → append a new entry at the bottom of the file.
4. **Entry exists** → update in place: increment **Iterations**, update **Updated**, replace **Prompt** with the refined prompt.
5. Never stack multiple versions. Only the latest prompt lives in the file.

## What counts as a substantial change

| Counts | Does NOT count |
|--------|---------------|
| New method or responsibility | Typo fix |
| New business requirement | Formatting change |
| Pattern change (e.g. @future → Queueable) | Single-line correction |
| Architectural refactor | Test assertion adjustment |
| New integration or dependency | Comment update |

## Register file reference

| File | Artifacts covered | Active profiles |
|------|------------------|-----------------|
| \`apex.md\` | Apex classes (.cls) | developer, architect |
| \`lwc.md\` | LWC (.js / .html / .js-meta.xml) | developer, ux |
| \`flows.md\` | Flows (.flow-meta.xml) | developer, admin, ba |
| \`triggers.md\` | Apex triggers + handlers (.trigger) | developer |
| \`visualforce.md\` | Visualforce pages and components | developer |
| \`aura.md\` | Aura components (.cmp / .app) | developer |
| \`omnistudio.md\` | OmniScripts, FlexCards, Integration Procedures | omnistudio |
| \`metadata.md\` | CustomObjects, CustomFields, ValidationRules, PermissionSets, CMDT, Platform Events, FlexiPages, NamedCredentials | developer, architect, admin, security |
| \`diagrams.md\` | Architecture diagrams (Mermaid / Lucid / draw.io) | architect, ba, ux, pm |
| \`cicd.md\` | Pipeline YAML, deployment scripts, GitHub Actions, Azure Pipelines | devops, mulesoft |
| \`docs.md\` | Generated documentation (ADRs, runbooks, data models, user guides) | architect, ba, ux, pm, devops, mulesoft, crma, data360, security |
| \`tests.md\` | Test plans, Playwright specs, Apex test classes | qa |

## Entry format

\`\`\`markdown
## <ComponentName>
- **Created:** YYYY-MM-DD
- **Updated:** YYYY-MM-DD   ← omit if never updated
- **Iterations:** N          ← increment on each substantial change

### Key decisions
- <Pattern / constraint / design choice that shaped the component>

### Prompt
\\\`\\\`\\\`
<the final prompt, summarized to key decisions if over 500 words>
\\\`\\\`\\\`
---
\`\`\`
`;
}
// ─── Register file content generators ─────────────────────────────────────
const HEADER = (version, title, types) => `<!-- setup-agents: ${version} -->
# ${title}

> AI prompt register for ${types} in this project.
> Maintained by the agent — one entry per component, latest prompt only.
> Commit this file so the team can trace every generated artifact back to its origin.

`;
const FORMAT = `## Format

\`\`\`
## <ComponentName>
- **Created:** YYYY-MM-DD
- **Updated:** YYYY-MM-DD   ← omit if never updated
- **Iterations:** N          ← increment on each substantial change

### Key decisions
- <Pattern / constraint / design choice that shaped the component>

### Prompt
\`\`\`
<the final prompt that produced or substantially changed this component>
\`\`\`
---
\`\`\`

**Substantial change** = new method, new business requirement, pattern change, architectural refactor.
Minor fixes (typos, formatting, single-line corrections) do NOT update the prompt entry.

---
`;
const FOOTER = `<!-- Entries below this line are maintained by the agent -->
`;
const FILE_BUILDERS = {
    'apex.md': (v) => HEADER(v, 'Apex Class Prompts', 'Apex classes (.cls)') +
        FORMAT +
        `## Usage

When creating a new Apex class, the agent reads this file for existing naming patterns,
data layer strategy, and sharing model decisions,
then generates the class consistent with prior entries.

When modifying an existing class substantially, the agent updates the entry in place
(increments **Iterations**, updates **Updated**, replaces **Prompt**).

---

` +
        FOOTER,
    'lwc.md': (v) => HEADER(v, 'Lightning Web Component Prompts', 'LWC components (.js / .html / .js-meta.xml)') +
        FORMAT +
        `## Usage

When creating a new LWC, the agent reads this file for existing SLDS patterns,
wire adapter choices, and Apex controller conventions, then generates the component
consistent with prior entries.

---

` +
        FOOTER,
    'flows.md': (v) => HEADER(v, 'Flow Prompts', 'Flows (.flow-meta.xml)') +
        FORMAT +
        `## Usage

When creating a new Flow, the agent reads this file for existing sub-flow patterns,
trigger contexts (Before Save / After Save), and object conventions.

Note: Flow XML conflicts must be resolved in Flow Builder. This register helps reconstruct intent.

---

` +
        FOOTER,
    'triggers.md': (v) => HEADER(v, 'Apex Trigger Prompts', 'Apex triggers (.trigger) and their handler classes') +
        FORMAT +
        `## Usage

When creating a new trigger+handler pair, the agent reads this file to:
- Verify no trigger already exists for that object (one trigger per object rule).
- Read existing handler patterns (Kevin O'Hara, delegation style, service class names).

Each entry covers both the trigger and its handler class.

---

` +
        FOOTER,
    'visualforce.md': (v) => HEADER(v, 'Visualforce Prompts', 'Visualforce pages (.page) and components (.component)') +
        FORMAT +
        `## Usage

When creating a new Visualforce page or component, the agent reads this file
for existing controller patterns and styling conventions.

---

` +
        FOOTER,
    'aura.md': (v) => HEADER(v, 'Aura Component Prompts', 'Aura components (.cmp / .app)') +
        FORMAT +
        `## Usage

When creating a new Aura component, the agent first checks whether an LWC equivalent
is possible (prefer LWC over Aura for new work), then reads this file for existing
event patterns and controller conventions.

---

` +
        FOOTER,
    'omnistudio.md': (v) => HEADER(v, 'OmniStudio Prompts', 'OmniScripts, FlexCards, and Integration Procedures (OmniStudio / Core)') +
        FORMAT +
        `## Usage

When creating OmniStudio artifacts, the agent reads this file for existing data source
patterns, action naming, and activation settings. It notes the deployment target:
OmniStudio managed package or OmniStudio for Core (Vlocity migration path).

---

` +
        FOOTER,
    'metadata.md': (v) => HEADER(v, 'Metadata Configuration Prompts', 'CustomObjects, CustomFields, ValidationRules, PermissionSets, CMDT, Platform Events, FlexiPages, NamedCredentials') +
        FORMAT +
        `## Usage

When creating declarative metadata, the agent reads this file for existing field naming
conventions (PascalCase API name, Spanish label), sharing model decisions, and CMDT patterns.

Use this file to reconstruct the business intent behind custom fields or validation rules
whose purpose is not obvious from the API name alone.

---

` +
        FOOTER,
    'diagrams.md': (v) => HEADER(v, 'Diagram Prompts', 'Architecture diagrams (Mermaid source, Lucid, draw.io)') +
        FORMAT +
        `## Usage

When creating a new diagram, the agent reads this file for existing diagram style
decisions (Mermaid type, Lucid vs draw.io, Kit of Parts usage, naming conventions)
and generates the diagram consistent with prior architectural decisions.

---

` +
        FOOTER,
    'cicd.md': (v) => HEADER(v, 'CI/CD & Pipeline Prompts', 'Pipeline YAML, deployment scripts, GitHub Actions workflows, Azure Pipelines, MuleSoft deployment descriptors') +
        FORMAT +
        `## Usage

When creating or modifying pipeline configuration, the agent reads this file for
existing stage structure, secret/variable naming, deployment target conventions,
and test gate thresholds already established in the project.

---

` +
        FOOTER,
    'docs.md': (v) => HEADER(v, 'Generated Documentation Prompts', 'ADRs, architecture review docs, runbooks, data model docs, user guides, release notes') +
        FORMAT +
        `## Usage

When generating documentation, the agent reads this file to understand the existing
documentation structure, naming conventions, and audience (technical, business, operations).
Always updates rather than duplicates an existing doc.

---

` +
        FOOTER,
    'tests.md': (v) => HEADER(v, 'Test Prompts', 'Test plans, Playwright specs, Apex test classes, MUnit tests') +
        FORMAT +
        `## Usage

When creating tests, the agent reads this file for existing PSG assignments used in
System.runAs(), fixture patterns, page object model structure, and coverage conventions.

---

` +
        FOOTER,
};
/** Returns the register files for the given profile IDs, keyed by filename. */
export function generateGeneratedPrompts(version, profileIds) {
    const filenames = profileIds ? promptRegistryFiles(profileIds) : Object.keys(FILE_BUILDERS);
    const result = {};
    for (const name of filenames) {
        const builder = FILE_BUILDERS[name];
        if (builder)
            result[name] = builder(version);
    }
    return result;
}
//# sourceMappingURL=generated-prompts-generator.js.map