"use strict";
// src/orchestrator/scaffold/TemplateRegistry.ts
// v1.16.0 — Lists + resolves scaffold templates.
//
// Two sources, in precedence order:
//   1. User-defined: `~/.openlife/templates/<id>/manifest.yaml`
//   2. Bundled:      `<openlife-install>/templates/<id>/manifest.yaml`
//
// User-defined wins on id collision, so users can override the bundled
// templates with their own variants.
//
// Each template directory MUST contain a `manifest.yaml` at the root.
// Any other files/dirs inside are the scaffold content (copied verbatim
// at apply time, with {{token}} substitution per ScaffoldEngine).
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.TemplateRegistry = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const yaml = __importStar(require("js-yaml"));
function userTemplatesDir() {
    // Respect OPENLIFE_STATE_DIR for testability.
    const explicit = process.env.OPENLIFE_STATE_DIR;
    if (explicit && explicit.trim())
        return path.join(explicit, 'templates');
    return path.join(os.homedir(), '.openlife', 'templates');
}
function bundledTemplatesCandidates() {
    return [
        // From repo checkout (cwd is openlife-core-main)
        path.join(process.cwd(), 'templates'),
        // From compiled dist when shipped in tarball (dist/orchestrator/scaffold/.. → repo root)
        path.join(__dirname, '..', '..', '..', 'templates'),
        path.join(__dirname, '..', '..', '..', '..', 'templates'),
    ];
}
function resolveBundledTemplatesDir() {
    for (const c of bundledTemplatesCandidates()) {
        if (fs.existsSync(c) && fs.statSync(c).isDirectory())
            return c;
    }
    return null;
}
function loadManifestFromDir(dir) {
    const manifestPath = path.join(dir, 'manifest.yaml');
    if (!fs.existsSync(manifestPath))
        return null;
    try {
        const raw = fs.readFileSync(manifestPath, 'utf-8');
        const parsed = yaml.load(raw);
        if (!parsed || typeof parsed.id !== 'string' || !parsed.name || !parsed.description) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
class TemplateRegistry {
    /**
     * Discover all templates (user + bundled). User wins on id collision.
     * Returns templates with `source` + `rootDir` populated.
     */
    list() {
        const byId = new Map();
        // Bundled first (so user can override).
        const bundledDir = resolveBundledTemplatesDir();
        if (bundledDir) {
            this.collectFromDir(bundledDir, 'bundled', byId);
        }
        const userDir = userTemplatesDir();
        if (fs.existsSync(userDir)) {
            this.collectFromDir(userDir, 'user', byId);
        }
        return Array.from(byId.values()).sort((a, b) => a.id.localeCompare(b.id));
    }
    /** Resolve a single template by id. Returns null when not found. */
    get(id) {
        return this.list().find(t => t.id === id) || null;
    }
    /** Exposed for tests + scaffold engine to know the rootDir. */
    static _userTemplatesDir() {
        return userTemplatesDir();
    }
    /** Exposed for tests. */
    static _bundledTemplatesCandidates() {
        return bundledTemplatesCandidates();
    }
    collectFromDir(dir, source, byId) {
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const ent of entries) {
            if (!ent.isDirectory())
                continue;
            const tplDir = path.join(dir, ent.name);
            const manifest = loadManifestFromDir(tplDir);
            if (!manifest)
                continue;
            manifest.source = source;
            manifest.rootDir = tplDir;
            // User overrides bundled at the same id.
            if (source === 'user' || !byId.has(manifest.id)) {
                byId.set(manifest.id, manifest);
            }
        }
    }
}
exports.TemplateRegistry = TemplateRegistry;
