import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

test("production startup wires pooled conversation title generation into sessions", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");

  assert.match(source, /const actionReceiptStore = createActionReceiptStore\(config\.dataDir\)/);
  assert.match(source, /initializeSessions\(config, undefined, \{[\s\S]*?actionReceiptStore,[\s\S]*?startRuntime: runtimePool\.startRuntime,[\s\S]*?generateConversationTitle: runtimePool\.generateConversationTitle[\s\S]*?\}\)/);
});

test("history list and open routes use the prewarmed account runtime", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");

  assert.match(source, /const historyRequester = runtimePool\?\.requestHistory/);
  assert.match(source, /listUnifiedThreads\(config, \{[\s\S]*?\}, historyRequester\)/);
  assert.match(source, /listAccountThreads\(config, accountId, \{[\s\S]*?\}, historyRequester\)/);
  assert.match(source, /openThread\(config, accountId, threadId, await readJson\(req\), readThreadFromPool\)/);
});

test("backend health starts before account runtimes prewarm in the background", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const listen = source.indexOf("server.listen(config.port");
  const prewarm = source.indexOf("void runtimePool?.prewarm()");

  assert.doesNotMatch(source, /await runtimePool\?\.prewarm\(\)/);
  assert.notEqual(listen, -1);
  assert.ok(prewarm > listen);
});

test("production startup restores managed local history before creating account services", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const restore = source.indexOf("await restoreLocalHistorySources(config, configPath)");
  const accountServices = source.indexOf("const accountLoginAttempts = await createAccountLoginAttempts");

  assert.notEqual(restore, -1);
  assert.ok(restore < accountServices);
  assert.match(source, /account_history_restore_deferred/);
});

test("production startup initializes one entitlement store and routes its authenticated API", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const configLoad = source.indexOf("await loadConfig()");
  const storeCreation = source.indexOf("createEntitlementStore(");
  const storeInitialization = source.indexOf("await entitlementStore.initialize()");
  const serverCreation = source.indexOf("createServer(");

  assert.match(source, /import \{ createEntitlementStore \} from "\.\/entitlement-store\.js"/);
  assert.match(source, /import \{ resolveEntitlementRoute \} from "\.\/entitlement-routes\.js"/);
  assert.ok(configLoad >= 0 && storeCreation > configLoad);
  assert.ok(storeInitialization > storeCreation && serverCreation > storeInitialization);
  assert.match(source, /resolveEntitlementRoute\(req, url, \{ store: entitlementStore, readJson \}\)/);
  assert.match(source, /createAccountLoginAttempts\(config, configPath, \{[\s\S]*?tokenUsageStore,[\s\S]*?assertCanAddExecutionAccount: \(\) => entitlementStore\.assertCanAddExecutionAccount\(\)[\s\S]*?\}\)/);
  assert.match(source, /resolveAccountRoute\(req, url, \{[\s\S]*?assertCanAddExecutionAccount: \(\) => entitlementStore\.assertCanAddExecutionAccount\(\)[\s\S]*?\}\)/);
  assert.match(source, /initializeSessions\(config, undefined, \{[\s\S]*?getAccountExecutionAccess: \(accountId\) => entitlementStore\.getAccountExecutionAccess\(accountId\)/);
  assert.match(source, /listPublicAccounts\(config, undefined, \(accountId\) => entitlementStore\.getAccountExecutionAccess\(accountId\)\)/);
});

test("GET /accounts only projects configured accounts and never rewrites configuration", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf('if (req.method === "GET" && url.pathname === "/accounts")');
  const routeEnd = source.indexOf("\n    const accountRoute", routeStart);
  const routeBody = source.slice(routeStart, routeEnd);

  assert.notEqual(routeStart, -1);
  assert.match(routeBody, /listPublicAccounts\(config,/);
  assert.doesNotMatch(routeBody, /pruneUnauthenticatedManagedAccounts|reconcileDuplicateAccounts|persist/i);
});

test("attachment responses use the server-detected type without browser sniffing", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf("const attachmentReadMatch");
  const routeEnd = source.indexOf("const approvalMatch", routeStart);
  const routeBody = source.slice(routeStart, routeEnd);

  assert.notEqual(routeStart, -1);
  assert.match(routeBody, /"content-type": attachment\.mimeType/);
  assert.match(routeBody, /"x-content-type-options": "nosniff"/);
  assert.match(routeBody, /"cache-control": "private, no-store"/);
});

test("DELETE attachment routes return only safe deletion metadata", async () => {
  const source = await readFile(new URL("./index.js", import.meta.url), "utf8");
  const routeStart = source.indexOf("const attachmentReadMatch");
  const routeEnd = source.indexOf("const approvalMatch", routeStart);
  const routeBody = source.slice(routeStart, routeEnd);

  assert.match(routeBody, /req\.method === "DELETE"/);
  assert.match(routeBody, /deleteAttachment\(getSession\(/);
  assert.match(routeBody, /sendJson\(res, 200, \{ deletion \}\)/);
});

test("HTTP and runtime operational logs use structured safe logging", async () => {
  const [indexSource, sessionsSource] = await Promise.all([
    readFile(new URL("./index.js", import.meta.url), "utf8"),
    readFile(new URL("./sessions.js", import.meta.url), "utf8")
  ]);

  assert.match(indexSource, /writeSafeLog\(console, "error", "request_failed", \{ error \}, config\)/);
  assert.doesNotMatch(indexSource, /console\.error\(error\)/);
  assert.match(sessionsSource, /writeSafeLog\(console, "warn", "codex_runtime_stderr", \{ text: data\.text \}, runtimeConfig\)/);
  assert.doesNotMatch(sessionsSource, /console\.warn\("Codex app-server:", data\.text\)/);
});

test("PC data reset is available only through the managed Windows host and preserves receipts", async () => {
  const [indexSource, resetSource] = await Promise.all([
    readFile(new URL("./index.js", import.meta.url), "utf8"),
    readFile(new URL("./application-data-reset.js", import.meta.url), "utf8")
  ]);

  assert.match(indexSource, /CODE_REMOTE_MANAGER_MANAGED_HOST === "1"/);
  assert.match(indexSource, /prepareSessionsForApplicationDataReset/);
  assert.match(indexSource, /deletePcApplicationData/);
  assert.doesNotMatch(resetSource, /action-receipts\.json/);
});
