/**
 * Prompt Path Resolution for AI Commands
 *
 * Prompts now live in @specverse/assets (a content-only leaf package); we
 * resolve there first. Falls back to the legacy __dirname-walk for
 * backwards compatibility with old engine builds that still bundled
 * prompts in engines/assets/prompts/ (engines ≤ 6.0.2).
 */
import { resolve, dirname, join } from 'path';
import { existsSync, readdirSync } from 'fs';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
/**
 * Resolve the prompts base directory — `<assets>/prompts/`.
 *
 * Priority:
 *   1. @specverse/assets package (the new home)
 *   2. Legacy engines/assets/prompts/ (back-compat fallback)
 */
function resolvePromptsBase() {
    // 1. Try @specverse/assets first.
    try {
        const pkg = require.resolve('@specverse/assets/package.json');
        const assetsBase = join(dirname(pkg), 'prompts');
        if (existsSync(join(assetsBase, 'core', 'standard'))) {
            return assetsBase;
        }
    }
    catch {
        /* @specverse/assets not installed — fall through to legacy path */
    }
    // 2. Fall back to engine-bundled prompts (engines ≤ 6.0.2).
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const legacyDirs = [
        resolve(__dirname, '../assets/prompts'), // From src/ to assets/ (development)
        resolve(__dirname, '../../assets/prompts'), // From dist/ to assets/ (built)
        resolve(__dirname, '../../../assets/prompts'), // From dist/commands/ to assets/
    ];
    for (const dir of legacyDirs) {
        if (existsSync(join(dir, 'core', 'standard'))) {
            return dir;
        }
    }
    return null;
}
/**
 * List frozen v<N>/ directories under core/standard/ for diagnostic output
 * when an unknown version is requested.
 */
function listAvailableFrozenVersions(promptsBase) {
    const standardDir = join(promptsBase, 'core/standard');
    if (!existsSync(standardDir))
        return [];
    try {
        return readdirSync(standardDir)
            .filter((name) => /^v\d+$/.test(name))
            .sort((a, b) => parseInt(a.slice(1), 10) - parseInt(b.slice(1), 10));
    }
    catch {
        return [];
    }
}
/**
 * Resolve prompt version to actual file system path
 */
export function resolvePromptPath(pver, _basePath) {
    const promptsBase = resolvePromptsBase();
    if (!promptsBase) {
        throw new Error('Could not locate prompts directory. Ensure @specverse/assets is installed (npm install @specverse/assets).');
    }
    // Resolve version to path. Accept 'default' (active iteration tip) or any
    // explicit major-version directory name (v9, v10, v11, ...).
    // Convention (see core/standard/README.md): default/ is the live directory
    // that ships the latest prompts; v<N>/ are FROZEN baselines kept for diff /
    // rollback / A-B testing. There is NO fallback from default → v<N> — if
    // default/ is missing, that's a packaging bug we want to surface, not paper
    // over. (The previous silent fallback shipped stale prompts unnoticed.)
    if (pver === 'default' || pver.match(/^v\d+$/)) {
        const versionPath = join(promptsBase, 'core/standard', pver);
        if (!existsSync(versionPath)) {
            throw new Error(`Prompt version '${pver}' not found at ${versionPath}. ` +
                (pver === 'default'
                    ? 'This indicates a broken @specverse/assets install — the default/ directory should always ship.'
                    : `Available frozen versions: ${listAvailableFrozenVersions(promptsBase).join(', ') || '(none)'}`));
        }
        return versionPath;
    }
    else if (pver.startsWith('custom=')) {
        const customPath = pver.substring(7); // Remove 'custom=' prefix
        return resolve(customPath);
    }
    else {
        throw new Error(`Invalid prompt version: ${pver}. Use default, v1, v2, v3, ... or custom=path`);
    }
}
/**
 * Validate that a prompt path exists and contains required prompt files
 */
export function validatePromptPath(promptPath, operation) {
    const errors = [];
    if (!existsSync(promptPath)) {
        errors.push(`Prompt path does not exist: ${promptPath}`);
        return { valid: false, errors };
    }
    // Check for required prompt files if operation is specified
    if (operation) {
        const requiredFile = join(promptPath, `${operation}.prompt.yaml`);
        if (!existsSync(requiredFile)) {
            errors.push(`Required prompt file not found: ${requiredFile}`);
        }
    }
    else {
        // Check for the canonical active prompt set. materialise + realize were
        // removed 2026-04-29 — they were vestigial whole-app/whole-deployment LLM
        // prompts replaced by deterministic instance factories + per-step
        // behavior generation (behavior.prompt.yaml).
        const requiredFiles = [
            'analyse.prompt.yaml',
            'create.prompt.yaml',
            'behavior.prompt.yaml',
            'verify-analyse.prompt.yaml',
            'verify-create.prompt.yaml',
        ];
        for (const file of requiredFiles) {
            const filePath = join(promptPath, file);
            if (!existsSync(filePath)) {
                errors.push(`Required prompt file not found: ${filePath}`);
            }
        }
    }
    return { valid: errors.length === 0, errors };
}
/**
 * Get available prompt versions
 */
export function getAvailablePromptVersions(_basePath) {
    try {
        const promptsBase = resolvePromptsBase();
        if (!promptsBase)
            return [];
        const standardPath = join(promptsBase, 'core', 'standard');
        if (!existsSync(standardPath))
            return [];
        const versions = [];
        const entries = readdirSync(standardPath, { withFileTypes: true });
        for (const entry of entries) {
            if (entry.isDirectory() && entry.name.match(/^v\d+$/)) {
                const versionPath = join(standardPath, entry.name);
                // Determine version description based on version number
                let description = `Prompts (${entry.name})`;
                if (entry.name === 'v2') {
                    description = 'Optimized Prompts (v2, 75% token reduction)';
                }
                else if (entry.name === 'v3') {
                    description = 'Three-Layer Architecture Prompts (v3)';
                }
                versions.push({
                    version: entry.name,
                    path: versionPath,
                    name: description,
                });
            }
        }
        // Sort versions by version number
        versions.sort((a, b) => {
            const aNum = parseInt(a.version.substring(1) || '1');
            const bNum = parseInt(b.version.substring(1) || '1');
            return aNum - bNum;
        });
        return versions;
    }
    catch (error) {
        return [];
    }
}
//# sourceMappingURL=prompt-loader.js.map