import type { ArtifactObligation, Turn } from "@best-agent/protocol";
import type { ConversationMessage, ProviderToolOption } from "../../provider/model-provider.js";
import {
  collectArtifactObligationFailures,
  compileArtifactObligations,
  hasCompletionGuardTool,
} from "../artifact-obligations.js";
import type { ProviderReplayRepairRuntime } from "./provider-replay-context.js";
import { findLatestUserMessage } from "./tool-constraint.js";

export function compileReplayArtifactObligations(input: {
  availableTools: ProviderToolOption[];
  cwd: string;
  messages: ConversationMessage[];
  objective?: string;
  payloadArtifactObligations?: ArtifactObligation[];
}): ArtifactObligation[] {
  if (!hasCompletionGuardTool(input.availableTools)) {
    return [];
  }
  return (
    input.payloadArtifactObligations ??
    compileArtifactObligations({
      artifactProducing: true,
      cwd: input.cwd,
      messages: input.messages,
      objective:
        input.objective ??
        findLatestUserMessage(input.messages) ??
        "Continue the current objective.",
    })
  );
}

export async function collectReplayArtifactObligationFailures(input: {
  artifactObligations: ArtifactObligation[];
  cwd: string;
  runtime: Pick<ProviderReplayRepairRuntime, "evidenceList">;
  turn: Turn;
}) {
  return collectArtifactObligationFailures(input.artifactObligations, input.cwd, {
    evidenceRecords: await input.runtime.evidenceList({
      threadId: input.turn.threadId,
      turnId: input.turn.id,
    }),
  });
}
