"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.DesignMdImporter = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
/** Filenames besides DESIGN.md that we propagate when richArtifacts=true. */
const RICH_ARTIFACT_FILES = [
    'tokens.json',
    'tokens-extended.json',
    'preview.html',
    'quality-score.json',
    'render-contract.json',
    'style-fingerprint.json',
    'agent-prompt.txt',
    'extraction-log.yaml',
    'telemetry.json',
];
class DesignMdImporter {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    /**
     * v1.15.0 — Unified import path that respects rich artifacts when available
     * and stays backward-compatible with the legacy DESIGN-only flow.
     */
    importProfilesFromDir(absProfilesDir, source, opts = {}) {
        const outBase = path.join(this.root, 'design', 'profiles');
        fs.mkdirSync(outBase, { recursive: true });
        if (!fs.existsSync(absProfilesDir))
            return [];
        const dirs = fs.readdirSync(absProfilesDir, { withFileTypes: true })
            .filter(d => d.isDirectory())
            .map(d => d.name);
        const metas = [];
        for (const d of dirs) {
            const srcDesign = path.join(absProfilesDir, d, 'DESIGN.md');
            if (!fs.existsSync(srcDesign))
                continue;
            const content = fs.readFileSync(srcDesign, 'utf-8');
            const checksum = crypto.createHash('sha256').update(content).digest('hex');
            const outDir = path.join(outBase, d);
            fs.mkdirSync(outDir, { recursive: true });
            fs.writeFileSync(path.join(outDir, 'DESIGN.md'), content, 'utf-8');
            const meta = {
                id: d,
                source,
                title: d,
                importedAt: new Date().toISOString(),
                checksum,
            };
            if (opts.richArtifacts !== false) {
                const copied = [];
                for (const name of RICH_ARTIFACT_FILES) {
                    const srcFile = path.join(absProfilesDir, d, name);
                    if (!fs.existsSync(srcFile))
                        continue;
                    try {
                        fs.copyFileSync(srcFile, path.join(outDir, name));
                        copied.push(name);
                    }
                    catch { /* skip individual artifact failures, keep DESIGN.md import */ }
                }
                if (copied.length)
                    meta.artifacts = copied;
                // Surface fingerprint archetype + quality letter into meta so the
                // registry can search/filter without re-reading every artifact.
                const fingerprintPath = path.join(absProfilesDir, d, 'style-fingerprint.json');
                if (fs.existsSync(fingerprintPath)) {
                    try {
                        const fp = JSON.parse(fs.readFileSync(fingerprintPath, 'utf-8'));
                        if (typeof fp?.archetype === 'string')
                            meta.archetype = fp.archetype;
                    }
                    catch { /* malformed JSON — skip */ }
                }
                const qualityPath = path.join(absProfilesDir, d, 'quality-score.json');
                if (fs.existsSync(qualityPath)) {
                    try {
                        const q = JSON.parse(fs.readFileSync(qualityPath, 'utf-8'));
                        if (typeof q?.letter === 'string')
                            meta.qualityScore = q.letter;
                        else if (typeof q?.grade === 'string')
                            meta.qualityScore = q.grade;
                    }
                    catch { /* malformed JSON — skip */ }
                }
            }
            fs.writeFileSync(path.join(outDir, 'meta.json'), JSON.stringify(meta, null, 2), 'utf-8');
            metas.push(meta);
        }
        return metas;
    }
    importFromVendor(vendorPath = 'vendor/awesome-design-md') {
        const absVendor = path.join(this.root, vendorPath, 'design-md');
        // Legacy default: DESIGN.md only, no rich artifacts (backward compatible).
        return this.importProfilesFromDir(absVendor, 'awesome-design-md', { richArtifacts: false });
    }
    importFromOpenDesign(openDesignPath = 'vendor/open-design') {
        const candidates = [
            path.join(this.root, openDesignPath, 'design-systems'),
            path.join(this.root, openDesignPath, 'packages', 'design-systems'),
        ];
        const existing = candidates.find((p) => fs.existsSync(p));
        if (!existing)
            return [];
        return this.importProfilesFromDir(existing, 'open-design');
    }
    /**
     * v1.15.0 — Pull a curated catalog of design profiles.
     *
     * - `core` (default): the 5-brand subset bundled in the npm tarball
     *   (`vendor/awesome-design-md-core/design-md/`). Always available
     *   offline. Includes rich artifacts.
     * - `full`: the full 72-brand collection. Resolved via, in order:
     *   1. explicit `opts.source` (absolute path or git url)
     *   2. env `OPENLIFE_DESIGN_CATALOG_PATH` (local dir)
     *   3. env `OPENLIFE_DESIGN_CATALOG_URL` (tarball/git url — TODO v1.15.1)
     * - Anything else is treated as a path/url override directly.
     */
    async pullCatalog(catalog = 'core', opts = {}) {
        const richArtifacts = opts.richArtifacts !== false;
        if (catalog === 'core') {
            const corePath = this.resolveBundledCore();
            if (!corePath) {
                throw new Error('core catalog not found in this distribution; reinstall or run `openlife doctor`');
            }
            return this.importProfilesFromDir(corePath, 'awesome-design-md-core', { richArtifacts });
        }
        if (catalog === 'full') {
            const localOverride = opts.source || process.env.OPENLIFE_DESIGN_CATALOG_PATH;
            if (localOverride && fs.existsSync(localOverride)) {
                // Accept either `<root>` (dirs are brands) or `<root>/design-md`.
                const profilesDir = fs.existsSync(path.join(localOverride, 'design-md'))
                    ? path.join(localOverride, 'design-md')
                    : localOverride;
                return this.importProfilesFromDir(profilesDir, 'awesome-design-md-full', { richArtifacts });
            }
            // Remote fetch is wired in v1.15.1. For now, give the user a clear
            // path: point at a local clone of the full catalog.
            throw new Error('full catalog requires OPENLIFE_DESIGN_CATALOG_PATH=<local-dir-of-72-brands> until remote pull lands in v1.15.1');
        }
        // Treat the value as a filesystem path.
        if (!fs.existsSync(catalog)) {
            throw new Error(`catalog path not found: ${catalog}`);
        }
        const profilesDir = fs.existsSync(path.join(catalog, 'design-md'))
            ? path.join(catalog, 'design-md')
            : catalog;
        return this.importProfilesFromDir(profilesDir, `path:${path.basename(catalog)}`, { richArtifacts });
    }
    /**
     * Find the bundled `awesome-design-md-core` regardless of whether we
     * run from source (cwd is repo) or from a global npm install (cwd is
     * the user's project, but the tarball lives under node_modules).
     */
    resolveBundledCore() {
        const candidates = [
            // From the repo (this.root is openlife-core-main checkout)
            path.join(this.root, 'vendor', 'awesome-design-md-core', 'design-md'),
            // From the compiled dist — package layout has vendor/ at root of tarball
            path.join(__dirname, '..', '..', 'vendor', 'awesome-design-md-core', 'design-md'),
            path.join(__dirname, '..', '..', '..', 'vendor', 'awesome-design-md-core', 'design-md'),
            // From the user's home if they extracted the catalog there
            path.join(os.homedir(), '.openlife', 'design-catalog', 'design-md'),
        ];
        for (const c of candidates) {
            if (fs.existsSync(c))
                return c;
        }
        return null;
    }
}
exports.DesignMdImporter = DesignMdImporter;
