import { BestAgentError } from "@best-agent/foundation";
import type { Turn } from "@best-agent/protocol";
import type { ConversationMessage } from "../../provider/model-provider.js";
import { buildPromptDeliverableRepairPrompt } from "../../prompt/runtime-prompts.js";
import type { ToolResumeContext } from "../checkpoint-codec.js";
import { collectPromptDeliverableFailures } from "../artifact-obligations.js";
import type { ProviderReplayRepairRuntime } from "./provider-replay-context.js";

export async function assertReplayToolOutputDeliverables(input: {
  payload: ToolResumeContext;
  repairMessages: ConversationMessage[];
  requiresDeliverableAssertion: boolean;
  runtime: Pick<ProviderReplayRepairRuntime, "assertArtifactObligationsSatisfied" | "cwd">;
  turn: Turn;
}): Promise<void> {
  if (!input.requiresDeliverableAssertion) {
    return;
  }
  if ((input.payload.artifactObligations?.length ?? 0) > 0) {
    await input.runtime.assertArtifactObligationsSatisfied(
      input.turn,
      input.payload.artifactObligations ?? [],
    );
    return;
  }
  const failures = collectPromptDeliverableFailures(input.repairMessages, input.runtime.cwd);
  if (failures.length > 0) {
    throw new BestAgentError(
      "PROVIDER_DECISION_INVALID",
      buildPromptDeliverableRepairPrompt(failures),
    );
  }
}
