/*
 * 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 { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ensureDir } from './file-writer.js';
export const PROJECT_KNOWLEDGE_PATH = '.setup-agents/project-knowledge.md';
export function projectKnowledgePath(cwd) {
    return join(cwd, PROJECT_KNOWLEDGE_PATH);
}
export function readProjectKnowledge(cwd) {
    const path = projectKnowledgePath(cwd);
    if (!existsSync(path))
        return null;
    return readFileSync(path, 'utf8');
}
export function projectKnowledgeExists(cwd) {
    return existsSync(projectKnowledgePath(cwd));
}
export function writeProjectKnowledge(cwd, content) {
    const path = projectKnowledgePath(cwd);
    ensureDir(join(cwd, '.setup-agents'));
    writeFileSync(path, content, 'utf8');
    return path;
}
export function generateProjectKnowledgeTemplate() {
    return `# Project Knowledge

This file is the single source of truth for architecture decisions, naming conventions,
and codebase structure. It is maintained by the architect role and consumed by all agents.

## Architecture Decisions

<!-- Record key decisions: data layer strategy, trigger pattern, async approach, sharing model -->
<!-- Example: "Data layer: Custom DynamicQueries utility class with inherited sharing" -->

## Naming Conventions

<!-- Record confirmed naming patterns for each artifact type -->
<!-- If not yet decided, the agent MUST ask the user before creating new artifacts -->

| Artifact | Convention | Example |
|----------|-----------|---------|
| Apex class | | |
| Test class | | |
| Trigger | | |
| Trigger handler | | |
| LWC | | |
| Custom object | | |
| Custom field | | |
| Flow | | |
| Permission set | | |

## Label Language

<!-- Which language to use for metadata labels and descriptions -->
<!-- Example: "Spanish for labels and descriptions, English for API names" -->

## Codebase Map

<!-- Key directories and what they contain -->
<!-- Entry points, service classes, utility classes, test helpers -->

## User Stories & Tasks

<!-- Active stories and tasks that provide context for current work -->
<!-- Updated by the workflow as stories progress -->

## Search Hints

<!-- Patterns and keywords to help agents find relevant files -->
<!-- Example: "Trigger handlers are in force-app/main/default/classes/*TriggerHandler.cls" -->
`;
}
export function appendTaskContext(cwd, storyId, summary, role) {
    const existing = readProjectKnowledge(cwd);
    if (!existing)
        return;
    const marker = '## User Stories & Tasks';
    const idx = existing.indexOf(marker);
    if (idx === -1)
        return;
    const roleSuffix = role ? ' (' + role + ')' : '';
    const entryLine = `- **${storyId}**${roleSuffix}: ${summary}`;
    if (existing.includes(entryLine))
        return;
    const markerEnd = existing.indexOf('\n\n', idx + marker.length);
    const insertAt = markerEnd !== -1 ? markerEnd : existing.length;
    const updated = existing.slice(0, insertAt) + '\n' + entryLine + existing.slice(insertAt);
    writeProjectKnowledge(cwd, updated);
}
export function projectKnowledgeRuleReference() {
    return [
        '',
        '## Project Knowledge (MANDATORY)',
        `- Before creating or modifying any Salesforce artifact, read \`${PROJECT_KNOWLEDGE_PATH}\` if it exists.`,
        '- It contains: architecture decisions, naming conventions, label language, and codebase map.',
        '- If the file does not exist or a section is empty, ASK the user before assuming conventions.',
        '- After an architecture decision is made, update the relevant section in project-knowledge.md.',
        `- For documentation lookups, read \`${DOC_INDEX_PATH}\` to find the right file without scanning the tree.`,
        `- For class/trigger/LWC lookups, read \`${CLASS_CATALOG_PATH}\` to find the right artifact by category.`,
    ];
}
// ─── Class Catalog ────────────────────────────────────────────────────────────
export const CLASS_CATALOG_PATH = '.setup-agents/class-catalog.md';
export function classCatalogPath(cwd) {
    return join(cwd, CLASS_CATALOG_PATH);
}
export function classCatalogExists(cwd) {
    return existsSync(classCatalogPath(cwd));
}
export function readClassCatalog(cwd) {
    const path = classCatalogPath(cwd);
    if (!existsSync(path))
        return null;
    return readFileSync(path, 'utf8');
}
export function writeClassCatalog(cwd, content) {
    const path = classCatalogPath(cwd);
    ensureDir(join(cwd, '.setup-agents'));
    writeFileSync(path, content, 'utf8');
    return path;
}
export function generateClassCatalogTemplate() {
    return `# Class Catalog

Categorized index of all Apex classes, triggers, and LWC components.
Agents read this to locate the right file without scanning the full tree.

## Domain Classes

<!-- Classes that encapsulate business logic for a specific object -->
| Class | Object | Purpose |
|-------|--------|---------|

## Service Classes

<!-- Classes that orchestrate cross-object operations or integrations -->
| Class | Responsibility |
|-------|---------------|

## Trigger Handlers

<!-- One trigger per object → handler mapping -->
| Trigger | Object | Handler |
|---------|--------|---------|

## Test Classes

<!-- Test → what it validates -->
| Test Class | Tests |
|-----------|-------|

## Invocable & REST

<!-- InvocableMethod, REST endpoints, Queueable, Batch, Schedulable -->
| Class | Type | Purpose |
|-------|------|---------|

## LWC Components

<!-- Lightning Web Components -->
| Component | Purpose |
|-----------|---------|

## Utilities

<!-- Shared helpers, selectors, factories, base classes -->
| Class | Purpose |
|-------|---------|
`;
}
// ─── Documentation Index ──────────────────────────────────────────────────────
export const DOC_INDEX_PATH = '.setup-agents/doc-index.md';
export function docIndexPath(cwd) {
    return join(cwd, DOC_INDEX_PATH);
}
export function docIndexExists(cwd) {
    return existsSync(docIndexPath(cwd));
}
export function readDocIndex(cwd) {
    const path = docIndexPath(cwd);
    if (!existsSync(path))
        return null;
    return readFileSync(path, 'utf8');
}
export function writeDocIndex(cwd, content) {
    const path = docIndexPath(cwd);
    ensureDir(join(cwd, '.setup-agents'));
    writeFileSync(path, content, 'utf8');
    return path;
}
export function generateDocIndexTemplate() {
    return `# Documentation Index

Agents read this file to know where project documentation lives.
Scan once, then use this index instead of searching the full tree.

| Path | Content | When to read |
|------|---------|--------------|
<!-- Populated by the project-knowledge-bootstrap skill -->
`;
}
//# sourceMappingURL=project-knowledge.js.map