"use strict";
// src/test_design_catalog_import.ts
// v1.15.0 — Phase A1 regression. Asserts:
//   1. pullCatalog('core') imports the 5 bundled brands with rich artifacts.
//   2. Rich artifacts (tokens.json, preview.html, etc.) propagate to design/profiles/.
//   3. SHA256 checksum is stable across re-imports.
//   4. style-fingerprint.json + quality-score.json surface into meta.json.
//   5. pullCatalog with a path override works.
//   6. pullCatalog('full') without override fails with an actionable error.
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 });
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const DesignMdImporter_1 = require("./design/DesignMdImporter");
function assert(cond, msg) {
    if (!cond)
        throw new Error(`assertion failed: ${msg}`);
}
function mkTmpRoot() {
    return fs.mkdtempSync(path.join(os.tmpdir(), 'design-import-'));
}
function rmTmp(dir) {
    try {
        fs.rmSync(dir, { recursive: true, force: true });
    }
    catch { /* */ }
}
function seedCoreCatalog(rootDir) {
    // Mimic vendor/awesome-design-md-core/design-md/ layout with 2 brands.
    const base = path.join(rootDir, 'vendor', 'awesome-design-md-core', 'design-md');
    for (const brand of ['fakelabs', 'mockcorp']) {
        const brandDir = path.join(base, brand);
        fs.mkdirSync(brandDir, { recursive: true });
        fs.writeFileSync(path.join(brandDir, 'DESIGN.md'), `# ${brand} DESIGN\n\nColors: blue + white.\n`);
        fs.writeFileSync(path.join(brandDir, 'tokens.json'), JSON.stringify({ primary: '#0000ff' }, null, 2));
        fs.writeFileSync(path.join(brandDir, 'preview.html'), `<html><body>${brand}</body></html>`);
        fs.writeFileSync(path.join(brandDir, 'style-fingerprint.json'), JSON.stringify({ archetype: 'minimal-blue' }, null, 2));
        fs.writeFileSync(path.join(brandDir, 'quality-score.json'), JSON.stringify({ letter: 'B' }, null, 2));
    }
}
async function scenarioCoreImport() {
    const tmp = mkTmpRoot();
    try {
        seedCoreCatalog(tmp);
        const imp = new DesignMdImporter_1.DesignMdImporter(tmp);
        const metas = await imp.pullCatalog('core');
        assert(metas.length === 2, `expected 2 imported brands, got ${metas.length}`);
        const profilesBase = path.join(tmp, 'design', 'profiles');
        assert(fs.existsSync(path.join(profilesBase, 'fakelabs', 'DESIGN.md')), 'fakelabs DESIGN.md missing');
        assert(fs.existsSync(path.join(profilesBase, 'fakelabs', 'tokens.json')), 'fakelabs tokens.json missing (rich artifacts not propagated)');
        assert(fs.existsSync(path.join(profilesBase, 'fakelabs', 'preview.html')), 'fakelabs preview.html missing');
        assert(fs.existsSync(path.join(profilesBase, 'fakelabs', 'meta.json')), 'fakelabs meta.json missing');
        const meta = JSON.parse(fs.readFileSync(path.join(profilesBase, 'fakelabs', 'meta.json'), 'utf-8'));
        assert(meta.source === 'awesome-design-md-core', `source should be awesome-design-md-core, got ${meta.source}`);
        assert(meta.archetype === 'minimal-blue', `archetype should be surfaced into meta, got ${meta.archetype}`);
        assert(meta.qualityScore === 'B', `qualityScore should be 'B', got ${meta.qualityScore}`);
        assert(Array.isArray(meta.artifacts) && meta.artifacts.includes('tokens.json'), 'artifacts list should include tokens.json');
        assert(typeof meta.checksum === 'string' && meta.checksum.length === 64, 'checksum should be 64-char hex');
    }
    finally {
        rmTmp(tmp);
    }
    console.log('✅ scenario 1: pullCatalog(core) imports rich artifacts + surfaces archetype/qualityScore');
}
async function scenarioChecksumStable() {
    const tmp = mkTmpRoot();
    try {
        seedCoreCatalog(tmp);
        const imp = new DesignMdImporter_1.DesignMdImporter(tmp);
        const m1 = await imp.pullCatalog('core');
        const m2 = await imp.pullCatalog('core');
        assert(m1.length === m2.length, 'count stable across re-import');
        const c1 = m1.find(m => m.id === 'fakelabs')?.checksum;
        const c2 = m2.find(m => m.id === 'fakelabs')?.checksum;
        assert(c1 && c2 && c1 === c2, `checksum should be stable: c1=${c1} c2=${c2}`);
    }
    finally {
        rmTmp(tmp);
    }
    console.log('✅ scenario 2: SHA256 checksum stable across re-imports');
}
async function scenarioPathOverride() {
    const tmp = mkTmpRoot();
    const catalogDir = mkTmpRoot();
    try {
        // Build a "user-provided" catalog at catalogDir/design-md/<brand>
        const dmDir = path.join(catalogDir, 'design-md');
        fs.mkdirSync(dmDir, { recursive: true });
        const brandDir = path.join(dmDir, 'externalbrand');
        fs.mkdirSync(brandDir);
        fs.writeFileSync(path.join(brandDir, 'DESIGN.md'), '# External\n');
        const imp = new DesignMdImporter_1.DesignMdImporter(tmp);
        const metas = await imp.pullCatalog(catalogDir);
        assert(metas.length === 1, `expected 1 brand from path override, got ${metas.length}`);
        assert(metas[0].id === 'externalbrand', `id should be externalbrand, got ${metas[0].id}`);
        assert(metas[0].source.startsWith('path:'), `source should start with 'path:', got ${metas[0].source}`);
    }
    finally {
        rmTmp(tmp);
        rmTmp(catalogDir);
    }
    console.log('✅ scenario 3: pullCatalog accepts arbitrary local path');
}
async function scenarioFullWithoutSourceErrors() {
    const tmp = mkTmpRoot();
    const prevEnv = process.env.OPENLIFE_DESIGN_CATALOG_PATH;
    delete process.env.OPENLIFE_DESIGN_CATALOG_PATH;
    try {
        const imp = new DesignMdImporter_1.DesignMdImporter(tmp);
        let err = null;
        try {
            await imp.pullCatalog('full');
        }
        catch (e) {
            err = e;
        }
        assert(err !== null, 'pullCatalog(full) without source must throw');
        assert(err.message.includes('OPENLIFE_DESIGN_CATALOG_PATH'), 'error must mention env override');
    }
    finally {
        if (prevEnv !== undefined)
            process.env.OPENLIFE_DESIGN_CATALOG_PATH = prevEnv;
        rmTmp(tmp);
    }
    console.log('✅ scenario 4: pullCatalog(full) without source emits actionable error');
}
async function scenarioBundledCoreOnRepo() {
    // Smoke against the real bundled core. If vendor/awesome-design-md-core/ is
    // not present (running outside a checkout), skip silently.
    const repoVendor = path.join(process.cwd(), 'vendor', 'awesome-design-md-core', 'design-md');
    if (!fs.existsSync(repoVendor)) {
        console.log('✓ scenario 5 skipped (running outside repo — no bundled core to test)');
        return;
    }
    const tmp = mkTmpRoot();
    try {
        const imp = new DesignMdImporter_1.DesignMdImporter(tmp);
        const metas = await imp.pullCatalog('core');
        assert(metas.length >= 5, `bundled core should have >=5 brands, got ${metas.length}`);
        const ids = metas.map(m => m.id).sort();
        for (const expected of ['apple', 'claude', 'stripe', 'vercel']) {
            assert(ids.includes(expected), `core must include ${expected}, got ${ids.join(',')}`);
        }
        console.log(`✅ scenario 5: bundled core imported ${metas.length} brands [${ids.join(', ')}]`);
    }
    finally {
        rmTmp(tmp);
    }
}
(async () => {
    try {
        await scenarioCoreImport();
        await scenarioChecksumStable();
        await scenarioPathOverride();
        await scenarioFullWithoutSourceErrors();
        await scenarioBundledCoreOnRepo();
        console.log('TEST_DESIGN_CATALOG_IMPORT_OK');
    }
    catch (err) {
        console.error('TEST_DESIGN_CATALOG_IMPORT_FAIL', err);
        process.exit(1);
    }
})();
