import { findSteerTraceConfirmation, steerDuplicateDecision, steerTraceText } from "../src/components/microservices/code-queue/src/steer-confirmation";
import type { QueueTask } from "../src/components/microservices/code-queue/src/types";

type JsonRecord = Record<string, unknown>;

function assertCondition(condition: unknown, message: string, detail: JsonRecord = {}): void {
  if (!condition) throw new Error(`${message}: ${JSON.stringify(detail)}`);
}

function fixtureTask(): QueueTask {
  const at = "2026-05-23T00:00:00.000Z";
  return {
    id: "codex_steer_confirm_fixture",
    queueId: "default",
    queueEnteredAt: at,
    prompt: "base",
    basePrompt: "base",
    referenceTaskIds: [],
    referenceInjection: null,
    providerId: "D601",
    cwd: "/workspace",
    model: "gpt-5.5",
    reasoningEffort: null,
    executionMode: "default",
    maxAttempts: 99,
    status: "running",
    createdAt: at,
    updatedAt: at,
    startedAt: at,
    finishedAt: null,
    readAt: null,
    currentAttempt: 1,
    currentMode: "initial",
    codexThreadId: "thread_fixture",
    activeTurnId: "turn_fixture",
    finalResponse: "",
    lastError: null,
    lastJudge: null,
    judgeFailCount: 0,
    promptHistory: [],
    output: [],
    events: [],
    attempts: [],
    cancelRequested: false,
    nextPrompt: null,
    nextMode: null,
  };
}

export function runCodeQueueSteerConfirmationContract(): JsonRecord {
  const task = fixtureTask();
  const steerId = "steer_contract_12345";
  const prompt = "correct this running task";
  task.output.push({ seq: 7, at: "2026-05-23T00:00:07.000Z", channel: "user", method: "turn/steer", itemId: steerId, text: steerTraceText(steerId, prompt) });
  task.promptHistory.push({ seq: 7, at: "2026-05-23T00:00:07.000Z", method: "turn/steer", text: prompt, steerId });

  const confirmation = findSteerTraceConfirmation(task, steerId);
  assertCondition(confirmation.found === true && confirmation.accepted === true, "confirmation should find steer trace by steerId", confirmation as unknown as JsonRecord);
  assertCondition(confirmation.matches.length === 1, "confirmation should coalesce promptHistory/output duplicates by seq", confirmation as unknown as JsonRecord);
  assertCondition(confirmation.trace?.promptChars === prompt.length, "confirmation should expose prompt chars without prompt text", (confirmation.trace ?? {}) as unknown as JsonRecord);
  assertCondition(JSON.stringify(confirmation).includes(prompt) === false, "confirmation must not echo prompt text", confirmation as unknown as JsonRecord);

  const duplicate = steerDuplicateDecision(task, steerId, prompt);
  assertCondition(duplicate.duplicate === true && duplicate.conflict === false, "same steerId and prompt should be duplicate-suppressed", duplicate as unknown as JsonRecord);

  const conflict = steerDuplicateDecision(task, steerId, "different prompt");
  assertCondition(conflict.duplicate === false && conflict.conflict === true, "same steerId with different prompt should be rejected as conflict", conflict as unknown as JsonRecord);

  const missing = findSteerTraceConfirmation(task, "steer_missing_12345");
  assertCondition(missing.found === false && missing.deliveryState === "unknown", "missing steerId should remain unknown", missing as unknown as JsonRecord);

  return {
    ok: true,
    checks: [
      "trace confirmation finds steer by steerId",
      "promptHistory/output duplicate seq is coalesced",
      "duplicate suppression requires same prompt hash",
      "steerId conflict is detectable",
      "missing steerId returns unknown",
    ],
  };
}

if (import.meta.main) {
  process.stdout.write(`${JSON.stringify(runCodeQueueSteerConfirmationContract(), null, 2)}\n`);
}
