"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadSkillsDir = loadSkillsDir;
exports.scanSkillsDir = scanSkillsDir;
exports.parseSkillFile = parseSkillFile;
exports.matchSkillTrigger = matchSkillTrigger;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
async function loadSkillsDir(skillsDir) {
    return (await scanSkillsDir(skillsDir)).skills;
}
async function scanSkillsDir(skillsDir) {
    const skills = [];
    const diagnostics = [];
    try {
        const entries = await fs.readdir(skillsDir, { withFileTypes: true });
        for (const entry of entries) {
            if (!entry.isDirectory())
                continue;
            // Skip internal directories like `_archive` (curator) and `_history` (undo
            // snapshots). They are scoped storage, not user-facing skills.
            if (entry.name.startsWith('_'))
                continue;
            const skillFile = path.join(skillsDir, entry.name, 'SKILL.md');
            try {
                const content = await fs.readFile(skillFile, 'utf-8');
                const skill = parseSkillFile(content, skillFile);
                if (skill) {
                    skills.push(skill);
                }
                else {
                    diagnostics.push({
                        name: entry.name,
                        filePath: skillFile,
                        reason: 'missing-frontmatter',
                        message: 'SKILL.md exists but does not start with YAML frontmatter.',
                    });
                }
            }
            catch (error) {
                const reason = await skillFileExists(skillFile) ? 'unreadable-skill-file' : 'missing-skill-file';
                diagnostics.push({
                    name: entry.name,
                    filePath: skillFile,
                    reason,
                    message: reason === 'missing-skill-file'
                        ? 'Skill folder is missing SKILL.md.'
                        : `Could not read SKILL.md: ${error instanceof Error ? error.message : String(error)}`,
                });
            }
        }
    }
    catch {
        // Skills directory doesn't exist — return empty
    }
    return { skills, diagnostics };
}
async function skillFileExists(filePath) {
    try {
        const stat = await fs.stat(filePath);
        return stat.isFile();
    }
    catch {
        return false;
    }
}
function parseSkillFile(content, filePath) {
    const frontmatter = extractFrontmatter(content);
    if (!frontmatter)
        return null;
    const riskRaw = typeof frontmatter.risk_level === 'string' ? frontmatter.risk_level.toLowerCase() : '';
    const riskLevel = riskRaw === 'low' || riskRaw === 'medium' || riskRaw === 'high' ? riskRaw : undefined;
    const enabledRaw = frontmatter.enabled;
    // Treat omitted field as enabled. Only the literal strings/booleans `false`/`'false'`
    // count as disabled, so existing skills without the field stay live.
    const enabled = enabledRaw === undefined
        ? undefined
        : !(enabledRaw === false || (typeof enabledRaw === 'string' && enabledRaw.toLowerCase() === 'false'));
    return {
        name: frontmatter.name ?? path.basename(path.dirname(filePath)),
        description: frontmatter.description ?? '',
        domain: frontmatter.domain ?? 'general',
        triggers: normalizeStringList(frontmatter.triggers),
        content: removeFrontmatter(content),
        filePath,
        whenToUse: typeof frontmatter.when_to_use === 'string' ? frontmatter.when_to_use : undefined,
        requiredTools: Array.isArray(frontmatter.required_tools) ? frontmatter.required_tools : undefined,
        riskLevel,
        steps: Array.isArray(frontmatter.steps) ? frontmatter.steps : undefined,
        examples: Array.isArray(frontmatter.examples) ? frontmatter.examples : undefined,
        validationChecks: Array.isArray(frontmatter.validation_checks) ? frontmatter.validation_checks : undefined,
        rollbackNotes: typeof frontmatter.rollback_notes === 'string' ? frontmatter.rollback_notes : undefined,
        enabled,
    };
}
function normalizeStringList(value) {
    if (Array.isArray(value))
        return value.filter((item) => typeof item === 'string');
    if (typeof value === 'string' && value.trim())
        return [value.trim()];
    return [];
}
function coerceYamlScalar(raw) {
    const trimmed = raw.trim();
    if (trimmed === '')
        return '';
    // Preserve quoted strings as strings.
    if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
        return trimmed.slice(1, -1);
    }
    if (trimmed === 'true')
        return true;
    if (trimmed === 'false')
        return false;
    if (trimmed === 'null' || trimmed === '~')
        return null;
    if (/^-?\d+$/.test(trimmed)) {
        const n = Number(trimmed);
        if (Number.isSafeInteger(n))
            return n;
    }
    if (/^-?\d+\.\d+$/.test(trimmed)) {
        const n = Number(trimmed);
        if (Number.isFinite(n))
            return n;
    }
    return trimmed;
}
function extractFrontmatter(content) {
    const match = content.match(/^---\n([\s\S]*?)\n---/);
    if (!match)
        return null;
    const yaml = match[1];
    const result = {};
    for (const line of yaml.split('\n')) {
        const colonIdx = line.indexOf(':');
        if (colonIdx === -1)
            continue;
        const key = line.slice(0, colonIdx).trim();
        const rawValue = line.slice(colonIdx + 1).trim();
        if (rawValue === '')
            continue;
        result[key] = coerceYamlScalar(rawValue);
    }
    // Parse triggers array (YAML list)
    const triggersMatch = yaml.match(/triggers:\n((?:\s+-\s+.+\n?)*)/);
    if (triggersMatch) {
        result.triggers = parseYamlList(triggersMatch[1]);
    }
    for (const key of ['required_tools', 'steps', 'examples', 'validation_checks']) {
        const re = new RegExp(`${key}:\\n((?:\\s+-\\s+.+\\n?)*)`);
        const m = yaml.match(re);
        if (m)
            result[key] = parseYamlList(m[1]);
    }
    return result;
}
function parseYamlList(block) {
    return block
        .trim()
        .split('\n')
        .map((line) => line.replace(/^\s*-\s*/, '').replace(/^"|"$/g, '').trim())
        .filter(Boolean);
}
function removeFrontmatter(content) {
    return content.replace(/^---\n[\s\S]*?\n---\n*/, '').trim();
}
function matchSkillTrigger(skills, userInput) {
    const normalized = userInput.toLowerCase().trim();
    for (const skill of skills) {
        if (skill.enabled === false)
            continue;
        for (const trigger of skill.triggers) {
            if (normalized.includes(trigger.toLowerCase())) {
                return skill;
            }
        }
    }
    return null;
}
//# sourceMappingURL=skillLoader.js.map