import type { ProviderConfig, Turn } from "@best-agent/protocol";
import type { AgentProfile } from "../../agent/profile-registry.js";
import type { ProviderToolOption } from "../../provider/model-provider.js";
import type { ProviderRequestCheckpointPayload } from "../checkpoint-codec.js";
import { buildReplayProviderTurnBudget } from "./provider-replay-budget.js";
import type { ProviderReplayRepairRuntime } from "./provider-replay-context.js";
import type { ProviderTurnBudget } from "./provider-turn-budget.js";

export type ReplayTerminalRepairState = {
  payload: ProviderRequestCheckpointPayload;
  replayContextAvailableTools?: ProviderToolOption[];
  replayProfile?: AgentProfile;
  replayProfileName?: string;
  replayProviderTurnBudget: ProviderTurnBudget;
  replayRouteConfig?: ProviderConfig;
  runtime: ProviderReplayRepairRuntime;
  turn: Turn;
};

export function buildReplayTerminalRepairState(input: {
  payload: ProviderRequestCheckpointPayload;
  runtime: ProviderReplayRepairRuntime;
  turn: Turn;
}): ReplayTerminalRepairState {
  const { payload, runtime, turn } = input;
  const replayRouteConfig = runtime.hydrateProviderRequestReplayConfig(payload);
  const replayContextAvailableTools = runtime.hydrateProviderReplayContextAvailableTools(payload);
  const replayProfileName = payload.replayContext?.profileName;
  const replayProfile = replayProfileName ? runtime.requireProfile(replayProfileName) : undefined;
  return {
    payload,
    replayContextAvailableTools,
    replayProfile,
    replayProfileName,
    replayProviderTurnBudget: buildReplayProviderTurnBudget({
      defaultMaxProviderTurns: runtime.defaultMaxProviderTurns,
      enabled: payload.replayContext?.providerTurnBudgeted ?? false,
      maxProviderTurnsForProfile: (profile) => runtime.maxProviderTurnsForProfile(profile),
      profile: replayProfile,
      providerTurnCount: payload.replayContext?.providerTurnCount,
    }),
    replayRouteConfig,
    runtime,
    turn,
  };
}
