import type {
  RunPhaseName,
  RunTurnResponse,
  StepId,
  ThreadId,
  ThreadMode,
  Turn,
  TurnId,
  WorkerLeaseStatus,
} from "@best-agent/protocol";
import type { ThreadStore } from "../../core/thread-store.js";

export type ToolTurnStateStore = {
  assertTurnAttemptWritable(turnId: TurnId): Promise<void>;
  getRunByTurn: ThreadStore["getRunByTurn"];
  getThreadMode(threadId: ThreadId): Promise<ThreadMode>;
  requireTurn(turnId: TurnId): Promise<Turn>;
};

export type ToolRunCheckpointStore = {
  completeRunCheckpoint(turnId: TurnId, workerLeaseStatus?: WorkerLeaseStatus): Promise<void>;
  completeRunCheckpointById(
    threadId: ThreadId,
    turnId: TurnId,
    checkpointId: StepId,
    workerLeaseStatus?: WorkerLeaseStatus,
  ): Promise<void>;
  getLatestTurnFailureMessage(turnId: TurnId): Promise<string | undefined>;
  leaveWaitPhase(
    turnId: TurnId,
    phaseName: RunPhaseName | undefined,
    reason: string,
  ): Promise<void>;
  updateRunControlForTurn(
    turnId: TurnId,
    control: { status: "paused" | "running"; waitReason: "ask-user" | "none" },
  ): Promise<void>;
};

export type ToolInterruptionStore = {
  createTurnTerminatedError(response: RunTurnResponse): Error;
  isInterrupted(turn: Turn): Promise<boolean>;
  isTurnTerminatedError(error: unknown): boolean;
  readTurnTerminatedResponse(error: unknown): RunTurnResponse | undefined;
};

export type ToolExecutionStore = ToolTurnStateStore &
  ToolRunCheckpointStore &
  ToolInterruptionStore;
