import type { Server } from "bun";
import { createHash } from "node:crypto";
import { mkdirSync } from "node:fs";
import { basename, isAbsolute } from "node:path";
import { dirname, join } from "node:path";
import { z } from "zod";
import {
  type ConfigLoadResult,
  dataDir,
  defaultConfig,
  isLocalFallbackAuthorized,
  loadConfigResult,
} from "./config";
import { directCommandIdentity } from "./command-identity";
import { ControllerFatalError } from "./config";
import { CapabilityService, type CapabilityProber } from "./capability";
import {
  buildJobReportConflictEvent,
  buildJobReportFinishedEvent,
  buildJobReportStartedEvent,
  buildSpineConfigInvalidEvent,
  buildSpineConfigMissingEvent,
  buildSpineConfigValidEvent,
} from "./events";
import { fetchHostLogs } from "./host-logs";
import { MetricsRegistry, type HostMetricsSampler, type TelemetryGap } from "./metrics";
import {
  IncidentReducer,
  type IncidentNotifier,
} from "./incidents";
import { ClusterScheduler } from "./scheduler";
import { buildControllerStatus, type ControllerStatus } from "./status";
import { ControllerStore, DeliveryEvidenceAdmissionService, type JobRecord } from "./store";
import { hasEvidenceAuthority, verifyEvidenceEnvelope, type EvidenceTrust, type ObservedDeploymentIdentity } from "./evidence";
import { TransitionEngine } from "./transitions";
import { DeliveryFeatureActivator } from "./delivery/activation";
import { LandRetirementService, LandOperationRequestSchema } from "./land-retirement";
import { DeployWatcher } from "./deploy-watcher";
import { loadTrackedRuntimeFeatureDefinitions, type LoadedFeatureDefinition } from "./delivery/definitions";
import { evaluateFeature, type ControllerReadinessDecision, type FeatureStateProvider } from "./delivery/features";
import {
  ArtifactManifestSchema,
  CreateWorkspaceInputSchema,
  RemoteJobLimitError,
  WorkspaceGcSchema,
  WorkspaceManager,
} from "./workspace";

export interface ControllerRuntime {
  store: ControllerStore;
  engine: TransitionEngine;
  scheduler: ClusterScheduler;
  capability: CapabilityService;
  deliveryActivator: DeliveryFeatureActivator;
  landRetirement: LandRetirementService;
  deployWatcher: DeployWatcher | null;
  configHealth: ConfigLoadResult;
}

export interface ServerOptions {
  host: string;
  port: number;
  token: string;
  store?: ControllerStore;
  engine?: TransitionEngine;
  scheduler?: ClusterScheduler;
  capability?: CapabilityService;
  configHealth?: ConfigLoadResult;
  dbPath?: string;
  metrics?: MetricsRegistry;
  metricsSampler?: HostMetricsSampler;
  hostLogsExec?: Parameters<typeof fetchHostLogs>[1];
  workspace?: WorkspaceManager;
  workspaceRoot?: string;
  capabilityProber?: CapabilityProber;
  incidents?: IncidentReducer;
  notifier?: IncidentNotifier;
  evidenceTrust?: EvidenceTrust;
  observedDeploymentIdentity?: ObservedDeploymentIdentity | null;
  deploymentSha?: string;
  landRetirement?: LandRetirementService;
}

const FULL_GIT_SHA = /^[0-9a-f]{40}$/;

export function resolveDeploymentSha(value: string | undefined): string | null {
  if (value === undefined || value === "") return null;
  if (!FULL_GIT_SHA.test(value)) {
    throw new Error("OVERDECK_DEPLOY_SHA must be a full lowercase 40-character git SHA");
  }
  return value;
}

function unauthorized(): Response {
  return new Response("unauthorized", { status: 401 });
}

function isAuthorized(req: Request, token: string): boolean {
  const header = req.headers.get("authorization");
  if (!header) return false;
  const match = /^Bearer (.+)$/.exec(header);
  if (!match) return false;
  return match[1] === token;
}

export function deliveryPreviewReadiness(
  store: ControllerStore,
  definition: LoadedFeatureDefinition,
  identity: ObservedDeploymentIdentity,
): ControllerReadinessDecision {
  const state = store.getDeliveryFeatureState(definition.definition.id);
  const deployment = store.getActiveDeliveryDeployment(identity.targetId);
  const acceptance = state?.acceptanceReceiptId ? store.getDeliveryFeatureReceipt(state.acceptanceReceiptId) : null;
  const smoke = state?.smokeReceiptId ? store.getDeliveryFeatureReceipt(state.smokeReceiptId) : null;
  const receiptBound = (receipt: NonNullable<typeof acceptance>) =>
    receipt.result === "PASSED"
    && receipt.featureId === definition.definition.id && receipt.definitionDigest === definition.digest
    && receipt.deploymentId === identity.deploymentId && receipt.targetId === "controller"
    && receipt.candidateSha === identity.deployedSha && receipt.deployedSha === identity.deployedSha
    && receipt.candidateTree === identity.deployedTree && receipt.deployedTree === identity.deployedTree
    && receipt.artifactDigest === identity.artifactDigest;
  const referencedReceiptMatches = (receipt: NonNullable<typeof acceptance>, kind: "ACCEPTANCE" | "SMOKE") =>
    receipt.receiptId === (kind === "ACCEPTANCE" ? state?.acceptanceReceiptId : state?.smokeReceiptId)
    && receipt.kind === kind && receiptBound(receipt);
  const admitted = Boolean(
    identity.targetId === "controller" && deployment
    && deployment.deploymentId === identity.deploymentId
    && deployment.targetId === "controller"
    && deployment.deployedSha === identity.deployedSha
    && deployment.deployedTree === identity.deployedTree
    && deployment.artifactDigest === identity.artifactDigest
    && acceptance && smoke
    && referencedReceiptMatches(acceptance, "ACCEPTANCE")
    && referencedReceiptMatches(smoke, "SMOKE")
    && definition.definition.readinessChecks.every((check) =>
      store.listDeliveryFeatureReceipts(definition.definition.id).some((receipt) => receipt.checkId === check && receiptBound(receipt))),
  );
  return admitted
    ? { admitted: true, deploymentId: identity.deploymentId, deployedSha: identity.deployedSha }
    : { admitted: false, reason: "exact active deployment and receipts required" };
}

export function deliveryPreviewResponse(
  store: FeatureStateProvider,
  definition: LoadedFeatureDefinition | undefined,
  identity: ObservedDeploymentIdentity | undefined,
  readiness?: ControllerReadinessDecision,
): Response {
  const evaluation = evaluateFeature(
    definition,
    store,
    { componentId: identity?.targetId ?? "controller", deployedSha: identity?.deployedSha ?? "" },
    readiness,
  );
  return evaluation.enabled
    ? Response.json({ capability: "controller-owned-dark-delivery" })
    : new Response("not found", { status: 404 });
}

function applyConfigHealth(store: ControllerStore, configHealth: ConfigLoadResult): void {
  if (configHealth.degraded && configHealth.incident) {
    store.emitConfigIncident(configHealth.incident.kind, configHealth.incident.detail);
  }
  if (isLocalFallbackAuthorized(configHealth)) {
    if (configHealth.localFallbackOverride && !configHealth.degraded) {
      store.recordLocalFallbackOverride();
    }
  }
}

export async function createControllerRuntime(options?: {
  dbPath?: string;
  configHealth?: ConfigLoadResult;
  capabilityProber?: CapabilityProber;
}): Promise<ControllerRuntime> {
  const configHealth = options?.configHealth ?? loadConfigResult();
  const dbPath =
    options?.dbPath ??
    join(dataDir(configHealth.config), "state.sqlite");
  mkdirSync(join(dbPath, ".."), { recursive: true });

  const store = new ControllerStore(dbPath);
  applyConfigHealth(store, configHealth);
  const capability = new CapabilityService(store, options?.capabilityProber);
  const scheduler = new ClusterScheduler(store, { recoverOrphans: true });
  const engine = new TransitionEngine(store, () => Date.now(), capability, scheduler);
  await engine.resumePending();
  const deliveryActivator = new DeliveryFeatureActivator(store, loadTrackedRuntimeFeatureDefinitions(), (featureId) => store.resolveDeliveryTarget(featureId));
  deliveryActivator.resumePending();
  deliveryActivator.reconcileExpired();
  const landRetirement = new LandRetirementService(store, { repositoryRoots: configHealth.config.landRepositoryRoots });
  landRetirement.reconcile();
  scheduler.reconcile();
  const deployWatcherConfig = configHealth.config.deployWatcher;
  const deployWatcher = deployWatcherConfig.enabled && deployWatcherConfig.deployDir && deployWatcherConfig.repoRoot
    ? new DeployWatcher(store, { deployDir: deployWatcherConfig.deployDir, repoRoot: deployWatcherConfig.repoRoot })
    : null;
  return { store, engine, scheduler, capability, deliveryActivator, landRetirement, deployWatcher, configHealth };
}

export function startServer(opts: ServerOptions): Server<undefined> {
  const { host, port, token } = opts;
  const deploymentSha = resolveDeploymentSha(opts.deploymentSha ?? process.env.OVERDECK_DEPLOY_SHA);
  const configHealth = opts.configHealth ?? loadConfigResult();
  const dbPath =
    opts.dbPath ?? join(dataDir(configHealth.config ?? defaultConfig()), "state.sqlite");

  const store = opts.store ?? new ControllerStore(dbPath);
  if (!opts.store) {
    applyConfigHealth(store, configHealth);
  }
  const capability = opts.capability
    ?? new CapabilityService(store, opts.capabilityProber);
  const scheduler = opts.scheduler ?? new ClusterScheduler(store, { recoverOrphans: true });
  const engine = opts.engine
    ?? new TransitionEngine(store, () => Date.now(), capability, scheduler);
  const landRetirement = opts.landRetirement ?? new LandRetirementService(store, { repositoryRoots: configHealth.config.landRepositoryRoots });
  if (!opts.engine) {
    void engine.resumePending();
  }
  if (!opts.scheduler) {
    scheduler.reconcile();
  }
  const incidents = opts.incidents ?? new IncidentReducer(
    store,
    opts.notifier ?? { notify: () => {} },
  );
  incidents.reducePending();
  const metrics = opts.metrics ?? new MetricsRegistry(
    store,
    opts.metricsSampler,
    undefined,
    {
      observe: (temperature) => incidents.observeTemperature(temperature, scheduler),
    },
  );
  const workspace = opts.workspace ?? (!opts.store || opts.workspaceRoot
    ? new WorkspaceManager(store, {
        rootDir: opts.workspaceRoot ?? join(dirname(dbPath), "workspaces"),
      })
    : undefined);

  const featureDefinitions = loadTrackedRuntimeFeatureDefinitions();
  let server: Server<undefined>;
  try {
    server = Bun.serve({
      hostname: host,
      port,
      async fetch(req) {
        const url = new URL(req.url);

        if (!isAuthorized(req, token)) {
          return unauthorized();
        }

        if (url.pathname === "/delivery/preview" && req.method === "GET") {
          const resolution = featureDefinitions.resolve("controller-owned-dark-delivery");
          const identity = opts.observedDeploymentIdentity ?? undefined;
          const definition = resolution.available ? resolution.definition : undefined;
          return deliveryPreviewResponse(
            store,
            definition,
            identity,
            definition && identity ? deliveryPreviewReadiness(store, definition, identity) : undefined,
          );
        }

        if (url.pathname === "/delivery/evidence" && req.method === "POST") {
          const evidenceTrust = opts.evidenceTrust
            ?? configHealth.config.deliveryEvidence;
          if (
            !evidenceTrust
            || evidenceTrust.authorityToken === token
            || !hasEvidenceAuthority(
              req.headers.get("x-delivery-evidence-authority"),
              evidenceTrust.authorityToken,
            )
          ) {
            return Response.json(
              { error: "delivery-evidence-admission-unavailable" },
              { status: 403 },
            );
          }
          try {
            const evidence = await verifyEvidenceEnvelope(
              await req.json(),
              evidenceTrust,
              Date.now(),
              opts.observedDeploymentIdentity ?? undefined,
            );
            new DeliveryEvidenceAdmissionService(store).admit(
              evidence.deployment,
              evidence.receipts,
              evidence.attestationId,
              evidence.installedProof,
            );
            return Response.json({ admitted: true }, { status: 201 });
          } catch {
            return Response.json(
              { error: "delivery-evidence-admission-rejected" },
              { status: 403 },
            );
          }
        }

        if (url.pathname === "/land/retire" && req.method === "POST") {
          return parseJson(req, LandOperationRequestSchema, (input) => {
            const operation = landRetirement.accept(input);
            return Response.json({
              operationId: operation.operationId,
              ticketId: operation.receipt.ticketId,
              fence: operation.fence,
              state: operation.state,
            }, { status: 202 });
          });
        }

        if (url.pathname === "/health" && req.method === "GET") {
          return Response.json({ ok: true, deployedSha: deploymentSha });
        }

        if (url.pathname === "/heartbeat" && req.method === "GET") {
          return Response.json({
            ok: true,
            revision: store.getRevision(),
            lastEventTs: store.getLastEventTimestamp(),
          });
        }

        if (url.pathname === "/status" && req.method === "GET") {
          const status = withTelemetryProbes(
            buildControllerStatus(store, configHealth),
            metrics.listTelemetryGaps(),
          );
          return Response.json(status);
        }

        if (url.pathname === "/metrics" && req.method === "GET") {
          return new Response(metrics.exposition(), {
            headers: { "content-type": "text/plain; version=0.0.4; charset=utf-8" },
          });
        }

        if (url.pathname === "/api/v1/query" && req.method === "GET") {
          const query = url.searchParams.get("query");
          if (!query) {
            return Response.json({ status: "error", error: "query is required" }, { status: 400 });
          }
          try {
            return Response.json(metrics.query(query));
          } catch (error) {
            return Response.json(
              { status: "error", error: (error as Error).message },
              { status: 400 },
            );
          }
        }

        if (workspace) {
          const workspaceResponse = handleWorkspaceRoute(req, url, workspace);
          if (workspaceResponse) {
            const response = await workspaceResponse;
            incidents.reducePending();
            return response;
          }
        }

        const hostLogsMatch = /^\/hosts\/([^/]+)\/logs$/.exec(url.pathname);
        if (hostLogsMatch && req.method === "GET") {
          const hostname = decodeURIComponent(hostLogsMatch[1] ?? "");
          const logs = fetchHostLogs(hostname, opts.hostLogsExec);
          if ("error" in logs) {
            if (logs.error === "invalid-hostname") {
              return Response.json({ error: "invalid-hostname" }, { status: 400 });
            }
            return Response.json({ error: "fetch-failed" }, { status: 502 });
          }
          return Response.json(logs);
        }

        if (url.pathname === "/admission/eligible" && req.method === "GET") {
          const host = url.searchParams.get("host") ?? "";
          const command = url.searchParams.get("command") ?? "";
          if (!host || !command) {
            return Response.json(
              { error: "invalid-args", detail: "host and command are required" },
              { status: 400 },
            );
          }
          return Response.json(store.hostEligible(host, command));
        }

        if (url.pathname === "/jobs/report" && req.method === "POST") {
          const response = await handleJobReport(req, store, capability);
          incidents.reducePending();
          return response;
        }

        if (url.pathname === "/spine/config/report" && req.method === "POST") {
          const response = await handleSpineConfigReport(req, store);
          incidents.reducePending();
          return response;
        }

        const transitionMatch = /^\/transition\/([^/]+)$/.exec(url.pathname);
        if (transitionMatch && req.method === "POST") {
          const verb = transitionMatch[1] ?? "";
          const response = await handleTransition(req, engine, verb);
          incidents.reducePending();
          return response;
        }

        return new Response("not found", { status: 404 });
      },
    });
  } catch (err) {
    const code = (err as { code?: string }).code;
    const message = (err as Error).message ?? String(err);
    if (code === "EADDRINUSE" || message.includes("EADDRINUSE") || message.includes("address already in use")) {
      throw new ControllerFatalError(
        "PORT_BUSY",
        `port ${port} on ${host} is already in use — refusing to auto-increment`,
      );
    }
    throw err;
  }

  return server;
}

function handleWorkspaceRoute(
  req: Request,
  url: URL,
  workspace: WorkspaceManager,
): Promise<Response> | null {
  if (req.method !== "POST") return null;
  if (url.pathname === "/workspace/create") {
    return parseJson(req, CreateWorkspaceInputSchema, (input) =>
      Response.json(workspace.create(input), { status: 201 }));
  }
  if (url.pathname === "/workspace/gc") {
    return parseJson(
      req,
      WorkspaceGcSchema,
      ({ ttlMs }) => Response.json({ collected: workspace.gc(ttlMs) }),
    );
  }
  const match = /^\/workspace\/([^/]+)\/(stage|promote)$/.exec(url.pathname);
  if (!match) return null;
  const jobId = decodeURIComponent(match[1] ?? "");
  if (match[2] === "stage") {
    return parseJson(req, ArtifactManifestSchema, (manifest) => {
      workspace.stage(jobId, manifest);
      return Response.json({ state: "staged" });
    });
  }
  return Promise.resolve().then(() => Response.json(workspace.promote(jobId))).catch(workspaceError);
}

async function parseJson<T>(
  req: Request,
  schema: { safeParse(value: unknown): { success: true; data: T } | { success: false } },
  handle: (value: T) => Response,
): Promise<Response> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return Response.json({ error: "invalid-args" }, { status: 422 });
  }
  const parsed = schema.safeParse(body);
  if (!parsed.success) {
    return Response.json({ error: "invalid-args" }, { status: 422 });
  }
  try {
    return handle(parsed.data);
  } catch (error) {
    return workspaceError(error);
  }
}

/**
 * A host with no machine numbers must say why. The telemetry read is a metrics-side concern,
 * so its gaps are joined onto the status probes here rather than duplicating the sampler.
 */
function withTelemetryProbes(
  status: ControllerStatus,
  gaps: readonly TelemetryGap[],
): ControllerStatus {
  const byHost = new Map(gaps.map((gap) => [gap.host, gap]));
  const hosts: ControllerStatus["hosts"] = {};
  for (const [hostname, host] of Object.entries(status.hosts)) {
    const gap = byHost.get(hostname);
    hosts[hostname] = {
      ...host,
      capability: {
        ...(host.capability ?? { probes: [] }),
        probes: [
          ...(host.capability?.probes ?? []),
          {
            name: "telemetry",
            ok: gap === undefined,
            ...(gap ? { detail: gap.reason } : {}),
            ...(gap?.at ? { checkedAt: gap.at } : {}),
          },
        ],
      },
    };
  }
  return { ...status, hosts };
}

function workspaceError(error: unknown): Response {
  if (error instanceof RemoteJobLimitError) {
    return Response.json({ error: "remote-job-limit" }, { status: 429 });
  }
  return Response.json(
    { error: "workspace-conflict", detail: (error as Error).message },
    { status: 409 },
  );
}

async function handleTransition(
  req: Request,
  engine: TransitionEngine,
  verb: string,
): Promise<Response> {
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return Response.json(
      { error: "invalid-args", detail: "request body must be JSON" },
      { status: 422 },
    );
  }

  if (!body || typeof body !== "object") {
    return Response.json(
      { error: "invalid-args", detail: "request body must be an object" },
      { status: 422 },
    );
  }

  const payload = body as {
    expectedRevision?: unknown;
    idempotencyKey?: string;
    args?: Record<string, unknown>;
  };

  const response = await engine.handle(verb, {
    expectedRevision: payload.expectedRevision,
    idempotencyKey: payload.idempotencyKey ?? "",
    args: payload.args,
  });

  return Response.json(response.body, { status: response.status });
}

const MirrorSchema = z.string().min(1).max(255).refine(
  (value) => !value.includes("/") && !value.includes("\\"),
  "mirror must not contain path separators",
);

const JobReportSchema = z.object({
  source: z.literal("remote-build"),
  host: z.string().min(1),
  key: z.string().min(1),
  mirror: MirrorSchema,
  repo: z.string().min(1),
  snapshot: z.string().min(1),
  argv: z.array(z.string()).min(1),
  attempt: z.number().int().positive(),
  stage: z.enum(["started", "finished"]),
  rc: z.number().int().optional(),
  startedAt: z.string().datetime(),
  finishedAt: z.string().datetime().optional(),
  timeoutSec: z.number().positive(),
  /** Set only by a remote executor that observed this exact command missing. */
  missingCommand: z.string().min(1).max(255).regex(/^[A-Za-z0-9._+-]+$/).optional(),
}).strict().superRefine((body, context) => {
  if (!basename(body.argv[0]!)) {
    context.addIssue({ code: z.ZodIssueCode.custom, message: "argv must contain a non-empty command" });
  }
  if (body.stage === "finished") {
    if (body.rc === undefined) {
      context.addIssue({ code: z.ZodIssueCode.custom, message: "rc is required when stage is finished" });
    }
    if (!body.finishedAt) {
      context.addIssue({ code: z.ZodIssueCode.custom, message: "finishedAt is required when stage is finished" });
    }
  }
  if (body.missingCommand !== undefined && body.stage !== "finished") {
    context.addIssue({ code: z.ZodIssueCode.custom, message: "missingCommand requires stage finished" });
  }
  if (body.missingCommand !== undefined && body.rc !== 126 && body.rc !== 127) {
    context.addIssue({ code: z.ZodIssueCode.custom, message: "missingCommand requires rc 126 or 127" });
  }
});

type JobReportBody = z.infer<typeof JobReportSchema>;

const SpineConfigMissingSchema = z.object({
  source: z.literal("remote-build"),
  stage: z.literal("missing"),
  configPath: z.string().min(1).refine(isAbsolute, "configPath must be absolute"),
  observedAt: z.string().datetime(),
}).strict();

const SpineConfigInvalidSchema = z.object({
  source: z.literal("remote-build"),
  stage: z.literal("invalid"),
  kind: z.enum(["config-invalid-json", "config-invalid-shape"]),
  detail: z.string(),
  configPath: z.string().min(1).refine(isAbsolute, "configPath must be absolute"),
  preservedPath: z.string().min(1).refine(isAbsolute, "preservedPath must be absolute"),
  observedAt: z.string().datetime(),
  override: z.boolean(),
}).strict();

const SpineConfigValidSchema = z.object({
  source: z.literal("remote-build"),
  stage: z.literal("valid"),
  configPath: z.string().min(1).refine(isAbsolute, "configPath must be absolute"),
  observedAt: z.string().datetime(),
  disabled: z.boolean(),
  override: z.boolean(),
}).strict();

const SpineConfigReportSchema = z.discriminatedUnion("stage", [
  SpineConfigMissingSchema,
  SpineConfigInvalidSchema,
  SpineConfigValidSchema,
]);

function deriveJobId(key: string, mirror: string): string {
  return createHash("sha256").update(key + mirror, "utf8").digest("hex");
}

function canonicalJson(value: unknown): string {
  if (value === null || typeof value !== "object") {
    return JSON.stringify(value);
  }
  if (Array.isArray(value)) {
    return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
  }
  const entries = Object.entries(value as Record<string, unknown>)
    .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
  return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
}

function bodyHash(body: unknown): string {
  return createHash("sha256").update(canonicalJson(body), "utf8").digest("hex");
}

const TERMINAL_JOB_STAGES = new Set(["succeeded", "failed", "completed", "blocked", "discarded", "cancelled"]);

function canonicalLifecycle(payload: {
  jobId: string;
  stage: "started" | "finished";
  attempt: number;
  rc: number | null;
  startedAt: string;
  finishedAt: string | null;
}): string {
  return JSON.stringify({
    jobId: payload.jobId,
    stage: payload.stage,
    attempt: payload.attempt,
    rc: payload.rc,
    startedAt: payload.startedAt,
    finishedAt: payload.finishedAt,
  });
}

function reportStageToStoredStage(stage: JobReportBody["stage"], rc?: number): string {
  if (stage === "started") return "running";
  return rc === 0 ? "succeeded" : "failed";
}

export async function handleJobReport(
  req: Request,
  store: ControllerStore,
  capability: CapabilityService,
): Promise<Response> {
  let raw: unknown;
  try {
    raw = await req.json();
  } catch {
    return Response.json({ error: "invalid-args", detail: "request body must be JSON" }, { status: 400 });
  }

  const parsed = JobReportSchema.safeParse(raw);
  if (!parsed.success) {
    return Response.json({ error: "invalid-args", detail: parsed.error.message }, { status: 400 });
  }
  const body = parsed.data;

  const jobId = deriveJobId(body.key, body.mirror);
  const receiptTs = new Date().toISOString();
  const persisted = store.getJob(jobId);
  const classification = classifyJobReport(jobId, body, persisted);

  if (classification.kind === "duplicate") {
    return Response.json({ ok: true, id: jobId, revision: store.getRevision() });
  }

  try {
    if (classification.kind === "conflict") {
      store.mutate(() => {
        store.appendEventInStore(buildJobReportConflictEvent({
          ts: receiptTs,
          jobId,
          repo: classification.persisted.repo,
          host: classification.persisted.host,
          snapshot: classification.persisted.snapshot,
          attempt: classification.attempt,
          rc: classification.persisted.rc,
          reportStage: body.stage,
        }));
      });
      return Response.json(
        { error: "job-report-conflict", id: jobId, stage: body.stage, attempt: classification.attempt },
        { status: 409 },
      );
    }

    const result = store.mutate(() => {
      if (!store.getHost(body.host)) {
        store.upsertHost({
          hostname: body.host,
          state: "maintenance",
          role: "builder",
          slotsTotal: 4,
          slotsUsed: 0,
          runningJobs: 0,
          ciJobsRunning: 0,
          healthStorage: true,
          healthRunner: true,
          healthOffload: true,
          capabilityOk: false,
          primary: false,
          enrolling: true,
          dispatchPaused: false,
          quarantinedCommands: [],
        });
      }

      const effectiveAttempt = classification.attempt;

      const storedStage = reportStageToStoredStage(body.stage, body.rc);
      const nextJob = {
        id: jobId,
        key: body.key,
        mirror: body.mirror,
        repo: body.repo,
        host: body.host,
        snapshot: body.snapshot,
        stage: storedStage,
        attempt: effectiveAttempt,
        rc: body.stage === "started" ? null : (body.rc ?? null),
        infraFailure: false,
        startedAt: body.startedAt,
        finishedAt: body.stage === "started" ? null : (body.finishedAt ?? null),
        lastReportAt: receiptTs,
        timeoutSec: body.timeoutSec,
      };
      store.upsertJob(nextJob);

      if (body.stage === "started") {
        store.appendEventInStore(buildJobReportStartedEvent({
          startedAt: body.startedAt,
          jobId,
          repo: body.repo,
          host: body.host,
          snapshot: body.snapshot,
          attempt: effectiveAttempt,
        }));
      } else {
        store.appendEventInStore(buildJobReportFinishedEvent({
          finishedAt: body.finishedAt!,
          startedAt: body.startedAt,
          jobId,
          repo: body.repo,
          host: body.host,
          snapshot: body.snapshot,
          attempt: effectiveAttempt,
          rc: body.rc!,
        }));
        const attributed = body.rc === 0
          ? directCommandIdentity(body.argv)
          : body.missingCommand ?? null;
        if (attributed) capability.recordExit(body.host, attributed, body.rc!);
      }

      return { id: jobId, revision: store.getRevision() };
    });
    return Response.json({ ok: true, id: result.id, revision: result.revision });
  } catch {
    return Response.json({ error: "report-write-failed" }, { status: 500 });
  }
}

function classifyJobReport(
  jobId: string,
  body: JobReportBody,
  persisted: JobRecord | null,
):
  | { kind: "applied"; attempt: number }
  | { kind: "duplicate"; attempt: number }
  | { kind: "conflict"; attempt: number; persisted: JobRecord } {
  const terminal = persisted ? TERMINAL_JOB_STAGES.has(persisted.stage) : false;
  const attempt = !persisted
    ? Math.max(1, body.attempt)
    : body.stage === "started" && terminal
      ? persisted.attempt + 1
      : persisted.attempt;
  if (!persisted) return { kind: "applied", attempt };

  const appliedStage = persisted.stage === "running"
    ? "started"
    : persisted.stage === "succeeded" || persisted.stage === "failed"
      ? "finished"
      : null;
  if (!appliedStage) return { kind: "applied", attempt };

  const incoming = canonicalLifecycle({
    jobId,
    stage: body.stage,
    attempt,
    rc: body.stage === "started" ? null : body.rc ?? null,
    startedAt: body.startedAt,
    finishedAt: body.stage === "started" ? null : body.finishedAt ?? null,
  });
  const applied = canonicalLifecycle({
    jobId,
    stage: appliedStage,
    attempt: persisted.attempt,
    rc: appliedStage === "started" ? null : persisted.rc,
    startedAt: persisted.startedAt ?? "",
    finishedAt: appliedStage === "started" ? null : persisted.finishedAt ?? null,
  });
  if (incoming === applied) return { kind: "duplicate", attempt };
  if (
    (body.stage === "finished" && persisted.stage === "running" && body.startedAt === persisted.startedAt) ||
    (body.stage === "started" && terminal)
  ) {
    return { kind: "applied", attempt };
  }
  return { kind: "conflict", attempt, persisted };
}

export async function handleSpineConfigReport(
  req: Request,
  store: ControllerStore,
): Promise<Response> {
  let raw: unknown;
  try {
    raw = await req.json();
  } catch {
    return Response.json({ error: "invalid-args", detail: "request body must be JSON" }, { status: 400 });
  }

  const parsed = SpineConfigReportSchema.safeParse(raw);
  if (!parsed.success) {
    return Response.json({ error: "invalid-args", detail: parsed.error.message }, { status: 400 });
  }
  const body = parsed.data;
  const hash = bodyHash(body);
  const existing = store.getSpineConfigState(body.configPath);
  if (existing?.lastAppliedBodyHash === hash) {
    return Response.json({ ok: true, revision: store.getRevision() });
  }

  try {
    const revision = store.mutate(() => {
      if (body.stage === "missing") {
        store.appendEventInStore(buildSpineConfigMissingEvent(body.observedAt));
      } else if (body.stage === "invalid") {
        store.appendEventInStore(buildSpineConfigInvalidEvent({
          observedAt: body.observedAt,
          kind: body.kind,
          override: body.override,
        }));
        const incidentKey = `spine-config:${body.configPath}`;
        const current = store.getIncident(incidentKey);
        store.upsertIncident({
          key: incidentKey,
          lastSeen: body.observedAt,
          affectedJobs: current?.affectedJobs ?? [],
          remediation: `Repair ${body.configPath}; preserved bytes: ${body.preservedPath}`,
          cooldownUntil: null,
          autoResolveCondition: `valid report for ${body.configPath}`,
          state: "open",
        });
        store.setSpineConfigDegraded(body.configPath);
      } else {
        store.appendEventInStore(buildSpineConfigValidEvent({
          observedAt: body.observedAt,
          disabled: body.disabled,
          override: body.override,
        }));
        const incidentKey = `spine-config:${body.configPath}`;
        store.resolveIncident(incidentKey, body.observedAt);
        store.restoreNormalControllerMeta(body.configPath);
      }
      store.setSpineConfigState({ configPath: body.configPath, lastAppliedBodyHash: hash });
      return store.getRevision();
    });
    return Response.json({ ok: true, revision });
  } catch {
    return Response.json({ error: "report-write-failed" }, { status: 500 });
  }
}
