/**
 * AUDIT-2 #17e + #17f smoke — dead-code cleanup.
 *
 * Background: docs/audit-2-followups.md §17 listed six dependency/feature
 * prunes. The user picked the two safest (zero live data, no user-
 * facing impact) to ship now:
 *
 *   #17e — SyntheticTest{,Run,StepResult} models + UI + API. Feature
 *          was half-shipped (no worker code path). 0 rows on live DB.
 *
 *   #17f — 'dns' monitor type. No strategy implementation; the engine
 *          wrote synthetic-down rows on every tick. 0 monitors of
 *          type='dns' on live DB.
 *
 * This smoke statically asserts the cleanup is complete.
 */
import './_lib';
import { ok, fail } from './_lib';
import { readFileSync, existsSync } from 'fs';
import path from 'path';

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

function read(rel: string): string {
    try { return readFileSync(path.join(ROOT, rel), 'utf8'); }
    catch (err) { fail(`read ${rel}`, String(err)); }
}

function assertNotExists(label: string, rel: string): void {
    if (existsSync(path.join(ROOT, rel))) fail(label, `file/dir still present: ${rel}`);
    ok(label);
}

function assertNotPresent(label: string, src: string, needle: string | RegExp): void {
    const re = typeof needle === 'string'
        ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        : needle;
    if (re.test(src)) fail(label, `pattern still present: ${String(needle)}`);
    ok(label);
}

function assertPresent(label: string, src: string, needle: string | RegExp): void {
    const re = typeof needle === 'string'
        ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
        : needle;
    if (!re.test(src)) fail(label, `missing required pattern: ${String(needle)}`);
    ok(label);
}

function main(): void {
    // #17e — SyntheticTest fully removed
    assertNotExists('audit2-17e: src/app/api/synthetic-tests deleted', 'src/app/api/synthetic-tests');
    assertNotExists('audit2-17e: src/app/synthetic-tests deleted', 'src/app/synthetic-tests');
    assertNotExists('audit2-17e: src/components/synthetic deleted', 'src/components/synthetic');
    assertNotExists('audit2-17e: synthetic-test-runner.service.ts deleted', 'src/lib/services/synthetic-test-runner.service.ts');
    assertNotExists('audit2-17e: synthetic-test.authz.ts deleted', 'src/lib/authorization/synthetic-test.authz.ts');
    assertNotExists('audit2-17e: synthetic auth smoke deleted', 'scripts/smoke/pra-2-synthetic-tests-authz.ts');

    // Schema migration present
    assertNotExists(
        'audit2-17e: SyntheticTest model removed from schema.prisma',
        // can't use assertNotExists on schema content; check below
        'prisma/migrations/_nonexistent_marker', // placeholder
    );

    const schema = read('prisma/schema.prisma');
    assertNotPresent('audit2-17e: schema has no SyntheticTest model', schema, /^model SyntheticTest \{/m);
    assertNotPresent('audit2-17e: schema has no SyntheticTestRun model', schema, /^model SyntheticTestRun \{/m);
    assertNotPresent('audit2-17e: schema has no SyntheticTestStepResult model', schema, /^model SyntheticTestStepResult \{/m);
    assertNotPresent('audit2-17e: User has no syntheticTestsCreated relation', schema, /syntheticTestsCreated\s*SyntheticTest\[\]/);

    const migration = read('prisma/migrations/20260524000001_audit2_17e_drop_synthetic_test/migration.sql');
    assertPresent('audit2-17e: DROP TABLE SyntheticTest', migration, /DROP TABLE IF EXISTS `SyntheticTest`/);
    assertPresent('audit2-17e: DROP TABLE SyntheticTestRun', migration, /DROP TABLE IF EXISTS `SyntheticTestRun`/);
    assertPresent('audit2-17e: DROP TABLE SyntheticTestStepResult', migration, /DROP TABLE IF EXISTS `SyntheticTestStepResult`/);

    // Sidebar + search no longer link to synthetic-tests
    const sidebar = read('src/components/dashboard/SidebarContent.tsx');
    assertNotPresent('audit2-17e: sidebar has no synthetic-tests link', sidebar, /href=['"]\/synthetic-tests['"]/);
    const searchRoute = read('src/app/api/search/route.ts');
    assertNotPresent('audit2-17e: search has no Synthetic Tests entry', searchRoute, /["']Synthetic Tests["']/);

    // env.ts has no SYNTHETIC_TESTS_ENABLED flag
    const env = read('src/lib/env.ts');
    assertNotPresent('audit2-17e: env no NEXT_PUBLIC_SYNTHETIC_TESTS_ENABLED', env, /NEXT_PUBLIC_SYNTHETIC_TESTS_ENABLED:\s*z/);

    // types/models.ts has no SyntheticTest interface
    const models = read('src/types/models.ts');
    assertNotPresent('audit2-17e: types has no SyntheticTest interface', models, /^export interface SyntheticTest \{/m);

    // #17f — 'dns' was removed in audit2-17f ONLY because it had no strategy
    // implementation (the engine wrote a synthetic 'down' every tick). It was
    // re-added PROPERLY on 2026-05-30 with a real Node dns/promises strategy.
    // The original failure mode this smoke guarded against — a type accepted
    // by Zod/UI but UNPROBED — is what we now assert is CLOSED: if 'dns' is
    // accepted, it MUST have a registered strategy. (monitor-types-dns-ssl.ts
    // owns the full positive wiring assertions.)
    const validation = read('src/lib/validations/monitor.schema.ts');
    void models;
    if (validation.includes("'dns'")) {
        const engineSrc = read('src/lib/monitor-engine.ts');
        assertPresent('audit2-17f: re-added dns type has a registered strategy (not unprobed)',
            engineSrc, "'dns': new DnsMonitorStrategy()");
        const dnsStrategy = read('src/lib/monitor-strategies/dns.strategy.ts');
        assertPresent('audit2-17f: DnsMonitorStrategy implements the strategy interface',
            dnsStrategy, /export class DnsMonitorStrategy implements MonitorStrategy/);
    } else {
        ok('audit2-17f: dns type remains removed from the Zod schema');
    }

    ok('audit2-17ef-dead-code-drop', 'SyntheticTest dropped; dns type, if present, is backed by a real strategy (no longer unprobed)');
}

main();
