// SPEC: PJ2026-0104010803 Workbench唯一投影 draft-2026-06-18-p0-unique-projection.
// Responsibility: Shared terminal seal authority helpers for Workbench store reducers.

import type { ChatMessage } from "@/types";
import { firstNonEmptyString } from "@/utils";
import { finalResponseText, messageText, normalizedStatusText } from "./workbench-message-projection-runtime";
import type { TurnStatusAuthority } from "./workbench-session";

export function traceAuthorityIsSealed(turn: TurnStatusAuthority | undefined, message: ChatMessage | null | undefined): boolean {
  return turnStatusAuthorityIsSealed(turn, message);
}

export function turnStatusAuthorityIsSealed(turn: TurnStatusAuthority | undefined, message: ChatMessage | null | undefined): boolean {
  if (!(turn?.terminal === true || isTerminalAuthorityStatus(turn?.status))) return false;
  return messageHasSealedTerminalResult(message);
}

export function messageIsSealedTerminal(message: ChatMessage | null | undefined): boolean {
  if (!message || message.role !== "agent") return false;
  return isTerminalAuthorityStatus(message.status) && messageHasSealedTerminalResult(message);
}

export function messageHasSealedTerminalResult(message: ChatMessage | null | undefined): boolean {
  if (!message || message.role !== "agent") return false;
  const record = message as Record<string, unknown>;
  const reply = recordValue(record.reply);
  return Boolean(firstNonEmptyString(
    messageText(message.text),
    messageText(record.content),
    finalResponseText(record.finalResponse),
    finalResponseText(record.reply),
    messageText(reply?.finalText),
    messageText(record.finalText),
    messageText(record.final)
  ));
}

function recordValue(value: unknown): Record<string, unknown> | null {
  return value && typeof value === "object" ? value as Record<string, unknown> : null;
}

function isTerminalAuthorityStatus(value: unknown): boolean {
  return [
    "completed",
    "failed",
    "blocked",
    "timeout",
    "canceled",
    "stale",
    "thread-resume-failed",
    "interrupted",
    "expired"
  ].includes(normalizeTerminalAuthorityStatus(value) ?? "");
}

function normalizeTerminalAuthorityStatus(value: unknown): string | null {
  const status = normalizedStatusText(value);
  if (status === "cancelled") return "canceled";
  if (status === "error") return "failed";
  return status;
}
