import { randomUUID } from "node:crypto";
import { join } from "node:path";
import { getConfigDir } from "../../config/paths";
import { issueServerLeaf } from "../../claude/intercept/local-ca";
import { startConnectProxy, type ConnectProxyHandle } from "../../claude/intercept/connect-proxy";
import { didRunOptionalShutdownHooks, registerOptionalShutdownHook } from "../../lib/optional-shutdown-hooks";
import { isTestHomeGuardArmed } from "../../lib/test-home-guard";
import { desktopOutboundFetch, desktopProxyFor } from "../../lib/desktop-proxy-route";
import { inspectDesktopCompatibilityAuthority, loadDesktopCompatibilityAuthority, type StoredDesktopAuthority } from "./certificate-store";
import { inspectWindowsCertificateTrust } from "./windows-certificate-trust";
import { createNativeIdentityReader } from "./native-identity";
import { UsageRelayController, type UsageIdentity } from "./usage-controller";
import { createUsageControlledFetch } from "./usage-controlled-fetch";
import { startDesktopRelay } from "./relay-listener";
import { launchWindowsCodexCompatibilityAsync } from "./windows-package-launch";
import { acquireDesktopCompatibilityRuntime, bindDesktopCompatibilityLaunch } from "./runtime-ownership";
import { createDesktopConnectionStore, type DesktopConnectionStore } from "./connection-store";
import { createNativeRoutingVerifier } from "./routing-preflight";
import { createInstalledBuildProbe, type DesktopBuildAssessment } from "./installed-build";

export { DESKTOP_COMPATIBILITY_ASSESSED_VERSION, isAssessedDesktopInstalled } from "./installed-build";
export interface DesktopRuntimeIo {
  platform?: string;
  loadAuthority?: () => Promise<StoredDesktopAuthority>;
  trust?: (authority: StoredDesktopAuthority) => Promise<"trusted" | "not-trusted" | "unknown">;
  identity?: ReturnType<typeof createNativeIdentityReader>;
  buildSupported?: () => boolean | Promise<boolean>;
  /** Internal fixture probe factory; requires testOnly and all sandbox identity/CA seams. */
  testOnlyBuildProbe?: () => ReturnType<typeof createInstalledBuildProbe>;
  upstreamFetch?: typeof fetch;
  connectionStore?: DesktopConnectionStore;
  routingSupported?: () => boolean;
  /** Synthetic-test execution is admitted only with explicit fixture identity and CA seams. */
  testOnly?: boolean;
}

/** Optional runtime. Import/construction/status do not start listeners or touch credentials. */
export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
  const platform = io.platform ?? process.platform;
  let buildProbe: ReturnType<typeof createInstalledBuildProbe> | undefined;
  let previousBuildAssessment: DesktopBuildAssessment | null = null;
  let boundBuild: { probe: ReturnType<typeof createInstalledBuildProbe>; revision: number } | null = null;
  let invalidateTrial: (() => void) | undefined;
  let contextEpoch = 0;
  const buildSupported = io.buildSupported ?? (() => buildProbe?.check() ?? Promise.resolve(false));
  let routingSupported = io.routingSupported ?? (() => false);
  let contextFailure: "build_unverified" | "native_routing_unverified" | null = null;
  const checkContext = async () => {
    const epoch = contextEpoch, probe = buildProbe;
    let binding: ReturnType<NonNullable<typeof probe>["binding"]> | null = null;
    try {
      if (!routingSupported()) { contextFailure = "native_routing_unverified"; invalidateTrial?.(); return null; }
      const supported = await buildSupported();
      // An old probe completion must not invalidate a replacement runtime's consent.
      if (epoch !== contextEpoch || probe !== buildProbe) return null;
      if (!io.buildSupported && probe) {
        binding = probe.binding();
        const changed = boundBuild?.probe === probe && boundBuild.revision !== binding.revision;
        boundBuild = { probe, revision: binding.revision };
        if (!supported || !binding.identity || changed) {
          contextFailure = "build_unverified"; invalidateTrial?.(); return null;
        }
      }
      contextFailure = !routingSupported() ? "native_routing_unverified" : !supported ? "build_unverified" : null;
    }
    catch {
      if (epoch !== contextEpoch || probe !== buildProbe) return null;
      contextFailure = "build_unverified";
    }
    if (contextFailure) invalidateTrial?.();
    return contextFailure === null ? { binding } : null;
  };
  const contextValid = async () => (await checkContext()) !== null;
  let phase: "off" | "starting" | "running" | "stopping" | "cleanup-required" = "off";
  type OwnedRuntime = { controller: UsageRelayController; close(): Promise<void>; pacUrl: string; fingerprint: string; deadline: number };
  let owned: OwnedRuntime | null = null;
  let closing: Promise<void> | null = null;
  let pendingCleanup: (() => Promise<void>) | null = null;
  let releaseOwner: (() => void) | null = null;
  let pendingLaunch: { owner: OwnedRuntime; abort: AbortController; revision: number | null;
    result: ReturnType<typeof launchWindowsCodexCompatibilityAsync> } | null = null;
  const status = () => ({ phase, supported: platform === "win32", running: owned !== null, contextFailure,
    ...(buildProbe ? { buildAssessment: buildProbe.lastResult() ?? (previousBuildAssessment ? { ...previousBuildAssessment } : null) } : {}),
    ...(owned ? { fingerprint: owned.fingerprint, safetyDeadline: owned.deadline, usage: owned.controller.snapshot() } : {}) });
  async function stop(): Promise<ReturnType<typeof status>> {
    if (phase === "starting") throw new Error("desktop_compatibility_busy");
    if (closing) { await closing; return status(); }
    if (!pendingCleanup) return status();
    contextEpoch++; invalidateTrial?.();
    phase = "stopping";
    closing = pendingCleanup().then(() => { owned = null; pendingCleanup = null; invalidateTrial = undefined; boundBuild = null;
      phase = "off"; releaseOwner?.(); releaseOwner = null; })
      .catch(error => { phase = "cleanup-required"; throw error; }).finally(() => { closing = null; });
    await closing; return status();
  }
  async function start() {
    if (phase !== "off") throw new Error("desktop_compatibility_busy");
    if (platform !== "win32") throw new Error("desktop_compatibility_unsupported");
    contextEpoch++; boundBuild = null; invalidateTrial = undefined;
    if (io.testOnlyBuildProbe && (!io.testOnly || io.buildSupported)) throw new Error("desktop_compatibility_test_environment");
    if ((isTestHomeGuardArmed() || io.testOnlyBuildProbe) && !(io.testOnly && io.identity && io.loadAuthority && io.trust && (io.buildSupported || io.testOnlyBuildProbe) && io.connectionStore && io.routingSupported)) throw new Error("desktop_compatibility_test_environment");
    if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping");
    try { desktopProxyFor(new URL("https://chatgpt.com")); } catch { throw new Error("desktop_compatibility_egress_proxy_invalid"); }
    releaseOwner = acquireDesktopCompatibilityRuntime(); phase = "starting";
    let relay: Awaited<ReturnType<typeof startDesktopRelay>> | undefined, proxy: ConnectProxyHandle | undefined;
    let pac: ReturnType<typeof Bun.serve> | undefined, timer: ReturnType<typeof setInterval> | undefined;
    let detach: (() => void) | undefined, unbindLaunch: (() => void) | undefined, controller: UsageRelayController | undefined;
    const cleanup = async () => {
      const launch = pendingLaunch;
      launch?.abort.abort();
      unbindLaunch?.();
      if (timer) clearInterval(timer); detach?.();
      // Abort transport before awaiting stream refresh so a stuck reader cannot retain sockets.
      const results = await Promise.allSettled([pac?.stop(true), proxy?.close(), relay?.close(), controller?.observeOnly(), buildProbe?.close(), launch?.result]);
      if (results.some(result => result.status === "rejected")) throw new Error("desktop_compatibility_cleanup_incomplete");
    };
    pendingCleanup = cleanup;
    try {
      if (!io.buildSupported) {
        // A fresh probe owns this start; diagnostics retain the last completed observation.
        previousBuildAssessment = buildProbe?.lastResult() ?? previousBuildAssessment;
        buildProbe = io.testOnlyBuildProbe ? io.testOnlyBuildProbe() : createInstalledBuildProbe();
      }
      if (!io.routingSupported) routingSupported = createNativeRoutingVerifier((await import("../paths")).getCodexHome());
      if (!await contextValid()) throw new Error(`desktop_compatibility_${contextFailure}`);
      const directory = join(getConfigDir(), "codex-desktop-compatibility");
      if (!io.loadAuthority) {
        const saved = inspectDesktopCompatibilityAuthority(directory);
        if (saved.status === "missing") throw new Error("desktop_compatibility_certificate_not_prepared");
        if (saved.status === "invalid") throw new Error("desktop_compatibility_certificate_invalid");
        if (saved.status === "expired") throw new Error("desktop_compatibility_certificate_expired");
      }
      const authority = await (io.loadAuthority?.() ?? loadDesktopCompatibilityAuthority({ directory }));
      const trust = await (io.trust?.(authority) ?? inspectWindowsCertificateTrust(authority.authority.certPem, authority.fingerprint));
      if (trust !== "trusted") throw new Error("desktop_compatibility_trust_required");
      const connections = io.connectionStore ?? createDesktopConnectionStore(directory);
      const previousConnection = connections.read();
      const deadline = authority.expiresAt - 300_000;
      if (deadline <= Date.now()) throw new Error("desktop_compatibility_certificate_expiring");
      const identity = io.identity ?? createNativeIdentityReader(join((await import("../paths")).getCodexHome(), "auth.json"), desktopOutboundFetch as typeof fetch);
      const account: UsageIdentity | null = await identity.verifyFreshIdentity();
      if (!account) throw new Error("desktop_compatibility_native_identity_unverified");
      if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping");
      controller = new UsageRelayController(account, identity.readCurrentIdentity, identity.verifyFreshIdentity, Date.now, deadline, 180000, contextValid);
      const trialController = controller;
      invalidateTrial = () => trialController.invalidateContext();
      relay = await startDesktopRelay({ leaf: issueServerLeaf(authority.authority, authority.commonName, ["chatgpt.com"]),
        fetchImpl: createUsageControlledFetch(controller, io.upstreamFetch ?? desktopOutboundFetch as typeof fetch) });
      try { proxy = await startConnectProxy(previousConnection?.connectPort ?? 0, { interceptPort: relay.port, interceptHosts: ["chatgpt.com"], allowedTargets: ["chatgpt.com:443"] }); }
      catch { throw new Error("desktop_compatibility_connection_unavailable"); }
      const runId = previousConnection?.id ?? randomUUID(), proxyPort = proxy.port;
      try { pac = Bun.serve({ hostname: "127.0.0.1", port: previousConnection?.pacPort ?? 0, fetch(req) {
        const url = new URL(req.url);
        if (req.method !== "GET" || req.headers.has("origin") || url.origin !== `http://127.0.0.1:${pac!.port}` || url.pathname !== `/${runId}/proxy.pac`) return new Response(null, { status: 404 });
        return new Response(`function FindProxyForURL(url, host) { return Date.now() < ${deadline} && host.toLowerCase() === "chatgpt.com" && url.indexOf("https:") === 0 ? "PROXY 127.0.0.1:${proxyPort}; DIRECT" : "DIRECT"; }`,
          { headers: { "content-type": "application/x-ns-proxy-autoconfig", "cache-control": "no-store" } });
      } }); } catch { throw new Error("desktop_compatibility_connection_unavailable"); }
      const connection = await connections.publish({ version: 1, id: runId, connectPort: proxyPort, pacPort: pac.port! });
      if (connection.id !== runId || connection.connectPort !== proxyPort || connection.pacPort !== pac.port) throw new Error("desktop_compatibility_connection_changed");
      if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping");
      const active = controller; let ticking = false, deadlineHandled = false, lastContextCheck = Date.now();
      timer = setInterval(() => {
        if (ticking) return; ticking = true;
        const expired = Date.now() >= deadline;
        const work = (async () => {
          const contextCadence = active.snapshot().mode === "apply" ? 10000 : 60000;
          if (!expired && Date.now() - lastContextCheck >= contextCadence) {
            lastContextCheck = Date.now();
            if (!await contextValid() && active.snapshot().mode === "apply") { await active.observeOnly(); return; }
          }
          await (expired && !deadlineHandled ? (deadlineHandled = true, active.observeOnly()) : active.expireIfNeeded());
        })();
        void work.catch(() => {}).finally(() => { ticking = false; });
      }, 1000); timer.unref();
      owned = { controller, close: cleanup, fingerprint: authority.fingerprint, deadline, pacUrl: `http://127.0.0.1:${pac.port}/${runId}/proxy.pac` };
      phase = "running";
      const launchedBy = owned;
      unbindLaunch = bindDesktopCompatibilityLaunch(owned.pacUrl, () => {
        if (owned !== launchedBy || phase !== "running" || Date.now() >= deadline || contextFailure) return null;
        const binding = buildProbe?.binding();
        return binding && binding.revision === boundBuild?.revision ? binding : null;
      }, () => {
        if (owned !== launchedBy || phase !== "running") return;
        // The restart adapter is synchronous. stop() revokes the trial and begins closing
        // listeners and sockets before yielding; failed cleanup stays visible on status.
        void stop().catch(() => {});
      });
      detach = registerOptionalShutdownHook("codex-desktop-compatibility", () => { void stop().catch(() => {}); });
      return status();
    } catch (error) {
      try { await cleanup(); pendingCleanup = null; invalidateTrial = undefined; boundBuild = null;
        phase = "off"; releaseOwner?.(); releaseOwner = null; }
      catch { phase = "cleanup-required"; throw new Error("desktop_compatibility_cleanup_incomplete"); }
      throw error;
    }
  }
  async function apply(accountWideConsent: boolean) {
    const current = owned;
    if (!current || phase !== "running") throw new Error("desktop_compatibility_not_running");
    const generation = current.controller.snapshot().generation, valid = await contextValid();
    if (owned !== current || phase !== "running") throw new Error("desktop_compatibility_not_running");
    if (!valid) { await current.controller.observeOnly(); throw new Error(`desktop_compatibility_${contextFailure}`); }
    if (generation !== current.controller.snapshot().generation) return { accepted: false, reason: "superseded", ...current.controller.snapshot() };
    const result = await current.controller.activate({ scope: "account-ui-compatibility", accountWideConsent });
    if (owned !== current || phase !== "running") { await current.controller.observeOnly(); return { ...result, accepted: false, reason: "runtime-stopped" }; }
    return result;
  }
  return { status, start, stop, apply,
    async observe() { if (owned) await owned.controller.observeOnly(); return status(); },
    async launch() {
      if (!owned || phase !== "running") throw new Error("desktop_compatibility_not_running");
      const current = owned;
      const verified = await checkContext();
      if (!verified) throw new Error(`desktop_compatibility_${contextFailure}`);
      if (owned !== current || phase !== "running") throw new Error("desktop_compatibility_not_running");
      const revision = verified.binding?.revision ?? null;
      if (revision !== null && buildProbe?.binding().revision !== revision) {
        throw new Error("desktop_compatibility_build_unverified");
      }
      if (!pendingLaunch || pendingLaunch.owner !== current) {
        const abort = new AbortController();
        pendingLaunch = { owner: current, abort, revision,
          result: launchWindowsCodexCompatibilityAsync(current.pacUrl, verified.binding?.build ?? null, { signal: abort.signal }) };
      }
      const launch = pendingLaunch;
      let result: Awaited<typeof launch.result>;
      try { result = await launch.result; }
      finally { if (pendingLaunch === launch) pendingLaunch = null; }
      // An old child cannot report success or stop a runtime that replaced its owner.
      if (owned !== current || phase !== "running") throw new Error("desktop_compatibility_not_running");
      // Success binds to the revision the child launched, which every joined caller must share.
      const stale = launch.revision !== revision || (revision !== null && buildProbe?.binding().revision !== revision);
      // A failed or indeterminate activation may have left a process on the managed connection,
      // so its still-current runtime is fenced even when the build revision moved meanwhile.
      if (result.status === "refused" && result.reason === "activation_failed") await stop();
      if (stale) throw new Error("desktop_compatibility_build_unverified");
      return result;
    },
    /** Internal native launch context; management status never returns the control endpoint. */
    getPacUrl: () => owned?.pacUrl ?? null,
  };
}
export type DesktopCompatibilityRuntime = ReturnType<typeof createDesktopCompatibilityRuntime>;
