import type { ProviderConfig, RunPhaseName } from "@best-agent/protocol";
import type { ProviderCorrectionTrace } from "../checkpoint-codec.js";
import type { ProviderTurnInvokeContext } from "./provider-turn-budget.js";
import type { RequiredToolConstraint } from "./tool-constraint-types.js";

export function buildProviderToolLoopContext(
  context: ProviderTurnInvokeContext,
  input: {
    correctionTrace?: ProviderCorrectionTrace;
    escalationLevel?: number;
    requiredToolConstraint?: RequiredToolConstraint;
    routeConfigOverride?: ProviderConfig;
    toolStepCount?: number;
  },
): ProviderTurnInvokeContext {
  return {
    ...context,
    downgradeEligible:
      context.downgradeEligible ?? isProviderToolLoopRoutingDowngradeEligible(context.phaseName),
    escalationLevel: input.escalationLevel,
    correctionTrace: input.correctionTrace ?? context.correctionTrace,
    requiredToolConstraint: input.requiredToolConstraint,
    routeConfigOverride: input.routeConfigOverride,
    toolStepCount: input.toolStepCount,
  };
}

export function isProviderToolLoopRoutingDowngradeEligible(phaseName?: RunPhaseName): boolean {
  return (
    phaseName === undefined ||
    phaseName === "inspect" ||
    phaseName === "summarize" ||
    phaseName === "wait"
  );
}
