/**
 * Boot-time helpers that wire the skills library into the running process.
 *
 * Skills come from four sources, in order of precedence (project > user >
 * learned > bundled). The same `SKILL.md` format is used for all four;
 * the Registry resolves any name conflict and reports shadows for the
 * `/skills` panel.
 *
 *   bundled  — `dist/skills-bundled/<name>/SKILL.md` (shipped with Franklin)
 *   learned  — `~/.blockrun/skills/learned/<id>/SKILL.md` (auto-generated by
 *              the learnings/extractor when a session yields a reusable
 *              procedure). Same disk format as the others — `hidden: true`
 *              keeps them out of `/help` but they still participate in
 *              trigger matching.
 *   user     — `~/.blockrun/skills/<name>/SKILL.md` (hand-authored per user)
 *   project  — `<workDir>/.franklin/skills/<name>/SKILL.md`
 *              and `<workDir>/.skills/<name>/SKILL.md`
 *
 * `getSkillVars` returns the runtime variables that
 * `substituteVariables` injects into a skill body before `$ARGUMENTS`
 * expansion. Only sync values live here; async (wallet balance, on-chain
 * reads) are deferred and the substituter leaves unknown vars literal.
 */
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { existsSync, mkdirSync } from 'node:fs';
import { loadSkillsFromDir } from './loader.js';
import { Registry } from './registry.js';
import { BLOCKRUN_DIR } from '../config.js';
import { migrateLegacyLearnedSkills } from '../learnings/store.js';
const HERE = dirname(fileURLToPath(import.meta.url));
// Built form lives at dist/skills/bootstrap.js, so dist/skills-bundled/
// is one level up + sibling.
const BUNDLED_DIR = join(HERE, '..', 'skills-bundled');
const USER_SKILLS_DIR = join(BLOCKRUN_DIR, 'skills');
const LEARNED_SKILLS_DIR = join(USER_SKILLS_DIR, 'learned');
function projectSkillDirs(workDir) {
    return [
        join(workDir, '.franklin', 'skills'),
        join(workDir, '.skills'),
    ];
}
/** Backwards-compatible alias: load only the bundled set. Callers should
 *  prefer `loadAllSkills(workDir)` to pick up user/project overrides. */
export function loadBundledSkills() {
    const result = loadSkillsFromDir(BUNDLED_DIR, 'bundled');
    return { registry: Registry.fromLoaded(result.skills), errors: result.errors };
}
/**
 * Discover every skill the user can run in this directory. Sources are
 * unioned; the Registry resolves name collisions by source precedence
 * (project > user > learned > bundled).
 */
export function loadAllSkills(workDir) {
    const errors = [];
    const all = [];
    const counts = {};
    // Fold any pre-unified-registry flat learned-skill files
    // (`~/.blockrun/skills/<name>.md`) into the new `learned/<name>/SKILL.md`
    // layout so upgrading users don't lose accumulated skills. No-op once done.
    try {
        migrateLegacyLearnedSkills();
    }
    catch { /* migration is best-effort */ }
    const sources = [
        { dir: BUNDLED_DIR, source: 'bundled' },
        { dir: LEARNED_SKILLS_DIR, source: 'learned' },
        { dir: USER_SKILLS_DIR, source: 'user' },
        ...projectSkillDirs(workDir).map((dir) => ({ dir, source: 'project' })),
    ];
    for (const { dir, source } of sources) {
        // user-global dir contains the `learned/` subdirectory — when loading
        // user-source, skip the learned subdirectory so it isn't loaded twice
        // with the wrong source label.
        if (source === 'user' && dir === USER_SKILLS_DIR) {
            const result = loadSkillsFromDir(dir, source);
            const filtered = result.skills.filter((l) => !l.path.startsWith(LEARNED_SKILLS_DIR));
            all.push(...filtered);
            errors.push(...result.errors);
            counts[source] = (counts[source] ?? 0) + filtered.length;
            continue;
        }
        const result = loadSkillsFromDir(dir, source);
        all.push(...result.skills);
        errors.push(...result.errors);
        counts[source] = (counts[source] ?? 0) + result.skills.length;
    }
    return { registry: Registry.fromLoaded(all), errors, counts };
}
/** Ensure the user-global skills root exists so `~/.blockrun/skills/<name>/`
 *  edits don't fail with ENOENT. Idempotent. */
export function ensureUserSkillsDir() {
    if (!existsSync(USER_SKILLS_DIR)) {
        mkdirSync(USER_SKILLS_DIR, { recursive: true });
    }
    return USER_SKILLS_DIR;
}
export function ensureLearnedSkillsDir() {
    if (!existsSync(LEARNED_SKILLS_DIR)) {
        mkdirSync(LEARNED_SKILLS_DIR, { recursive: true });
    }
    return LEARNED_SKILLS_DIR;
}
export function getSkillVars(src) {
    const out = {};
    if (src.chain)
        out.wallet_chain = src.chain;
    return out;
}
