/**
 * ui-primitive-adoption (T9, 2026-06-02) — replaces auditor-button-primitive-gone.
 *
 * The 2026-06-01 deletion removed an UNUSED, aspirational Button primitive
 * (1 importer, tokens that existed only under /executive). T9 reintroduces a
 * token-backed primitive — but only earns that reversal by ADOPTING it. This
 * smoke is the inverse guard:
 *   1. the Button primitive exists and is exported from the ui barrel,
 *   2. the raw <button> count only ever RATCHETS DOWN (never above the ceiling).
 *
 * Each migration phase LOWERS RAW_BUTTON_CEILING to the new count. Never raise
 * it — that would let the codebase slide back toward bespoke copy-paste markup.
 */
import './_lib';
import { ok, fail } from './_lib';
import { existsSync, readFileSync, readdirSync } from 'fs';
import path from 'path';

const ROOT = path.resolve(__dirname, '../..');

// Ratchet ceiling — LOWER this with each migration phase; never raise it.
// Counts FEATURE-code raw <button> only; src/components/ui/ (the primitive
// library) is the sanctioned home of <button> and is excluded.
const RAW_BUTTON_CEILING = 21;
const UI_DIR = path.resolve(ROOT, 'src/components/ui');

function countRawButtons(dir: string): number {
    let n = 0;
    for (const entry of readdirSync(dir, { withFileTypes: true })) {
        const p = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            if (path.resolve(p) === UI_DIR) continue; // skip the primitive library
            n += countRawButtons(p);
        } else if (entry.name.endsWith('.tsx')) {
            n += (readFileSync(p, 'utf8').match(/<button[\s>]/g) ?? []).length;
        }
    }
    return n;
}

function main(): void {
    if (!existsSync(path.join(ROOT, 'src/components/ui/Button.tsx'))) {
        fail('ui-primitive-adoption: Button primitive exists', 'src/components/ui/Button.tsx missing');
    }
    const barrel = readFileSync(path.join(ROOT, 'src/components/ui/index.ts'), 'utf8');
    if (!/export\s+\{[^}]*\bButton\b/.test(barrel)) {
        fail('ui-primitive-adoption: Button exported from barrel', 'src/components/ui/index.ts does not export Button');
    }
    ok('ui-primitive-adoption: Button primitive present and exported from the ui barrel');

    const raw = countRawButtons(path.join(ROOT, 'src/components'));
    if (raw > RAW_BUTTON_CEILING) {
        fail(
            'ui-primitive-adoption: raw <button> ratchet',
            `found ${raw} raw <button> in src/components, ceiling is ${RAW_BUTTON_CEILING} — migrate to <Button> or lower the ceiling deliberately`,
        );
    }
    ok('ui-primitive-adoption', `raw <button> count ${raw} <= ratchet ceiling ${RAW_BUTTON_CEILING}`);
}

main();
