import { readFileSync } from "node:fs";
import { resolve } from "node:path";

function assert(condition: boolean, message: string): void {
    if (!condition) {
        throw new Error(message);
    }
}

async function main(): Promise<void> {
    const root = process.cwd();
    const adminHtml = readFileSync(resolve(root, "src/web/static/admin.html"), "utf8");
    const setupHtml = readFileSync(resolve(root, "src/web/static/setup.html"), "utf8");
    const overlayHtml = readFileSync(resolve(root, "src/web/static/overlay.html"), "utf8");
    const indexTs = readFileSync(resolve(root, "src/index.ts"), "utf8");

    assert(adminHtml.includes("Conduit Admin"), "Expected admin page title markup.");
    assert(setupHtml.includes("Conduit Setup"), "Expected setup page title markup.");
    assert(!adminHtml.includes("First-Time Setup Wizard"), "Expected setup UI to be separate from admin page.");
    assert(!adminHtml.includes("YOUR_ADMIN_TOKEN"), "Expected admin page not to instruct query-token URLs.");
    assert(adminHtml.includes("sessionStorage"), "Expected admin token to be stored in sessionStorage.");
    assert(adminHtml.includes("function scheduleReconnect"), "Expected admin WebSocket reconnect scheduler.");
    assert(adminHtml.includes("hasConnectedOnce"), "Expected reconnect to require at least one successful connection.");
    assert(adminHtml.includes("RECONNECT_MAX_MS"), "Expected bounded reconnect backoff.");
    assert(adminHtml.includes("clearReconnectTimer()"), "Expected reconnect timer cleanup.");
    assert(adminHtml.includes("dev-only dev-hidden"), "Expected dev controls to be hidden by default.");
    assert(adminHtml.includes("function applyEnvironmentMode"), "Expected NODE_ENV-driven admin UI gating.");
    assert(adminHtml.includes('appEnv = "production"'), "Expected production-safe default admin UI mode.");
    assert(setupHtml.includes("/setup/auth"), "Expected setup page to post setup auth requests.");
    assert(setupHtml.includes("/setup/complete"), "Expected setup page to post setup completion requests.");
    assert(setupHtml.includes("setup-admin-token"), "Expected setup page to show admin token separately.");
    assert(setupHtml.includes("setup-overlay-row"), "Expected setup page to conditionally render overlay access.");
    assert(overlayHtml.includes("Conduit Overlay"), "Expected overlay page title markup.");
    assert(
        adminHtml.includes("/ws?token=") && overlayHtml.includes("/ws?token="),
        "Expected WebSocket token auth to remain wired."
    );
    assert(
        !adminHtml.includes("li.innerHTML = `<span class=\"meta\">"),
        "Expected admin chat rows to avoid rendering untrusted chat content with innerHTML."
    );
    assert(
        adminHtml.includes("authorStrong.textContent = author") &&
            adminHtml.includes("messageSpan.textContent = message"),
        "Expected admin chat author/message to render via textContent."
    );
    assert(indexTs.includes('url.pathname === "/admin"'), "Expected /admin route wiring.");
    assert(indexTs.includes('url.pathname === "/setup"'), "Expected /setup route wiring.");
    assert(indexTs.includes('url.pathname === "/overlay"'), "Expected /overlay route wiring.");
    assert(indexTs.includes('env.NODE_ENV !== "production"'), "Expected overlay to be gated outside production.");
    assert(indexTs.includes('url.pathname === "/robots.txt"'), "Expected /robots.txt route wiring.");
    assert(indexTs.includes('"x-robots-tag"'), "Expected X-Robots-Tag response header.");
    assert(indexTs.includes('"content-security-policy"'), "Expected Content-Security-Policy response header.");
    assert(indexTs.includes('"cache-control": "no-store"'), "Expected app responses to include no-store cache policy.");
    assert(indexTs.includes("Server is shutting down."), "Expected late HTTP requests during shutdown to be rejected.");
    assert(indexTs.includes("closeIdleConnections"), "Expected shutdown to close idle HTTP keep-alive connections.");
    assert(indexTs.includes("closeAllConnections"), "Expected shutdown to have a bounded forced close fallback.");

    console.log(
        JSON.stringify(
            {
                ok: true,
                checks: [
                    "admin_html",
                    "setup_html",
                    "setup_separate_from_admin",
                    "admin_token_prompt",
                    "admin_ws_reconnect",
                    "admin_env_gating",
                    "overlay_html",
                    "overlay_env_gating",
                    "admin_chat_text_content",
                    "admin_route",
                    "setup_route",
                    "overlay_route",
                    "robots_route",
                    "security_headers",
                    "no_store_cache_policy",
                    "shutdown_http_cleanup"
                ]
            },
            null,
            2
        )
    );
}

main().catch((error: unknown) => {
    const message = error instanceof Error ? error.message : String(error);
    console.error(message);
    process.exit(1);
});
