import type { PhaseResultPhaseName, ProviderTurnActionPolicy } from "@best-agent/protocol";
import { BestAgentError } from "@best-agent/foundation";

export type ProviderStructuredControls = {
  allowPhaseResult?: boolean;
  allowPlanUpdate?: boolean;
  phaseResultPhaseName?: PhaseResultPhaseName;
};

export type EffectiveProviderStructuredControls = {
  allowPhaseResult: boolean;
  allowPlanUpdate: boolean;
  phaseResultPhaseName?: PhaseResultPhaseName;
};

export function deriveControlsForActionPolicy(
  controls: ProviderStructuredControls,
  actionPolicy: ProviderTurnActionPolicy,
): EffectiveProviderStructuredControls {
  if (
    controls.allowPhaseResult &&
    actionPolicy.allowedActions.includes("phase_result") &&
    !controls.phaseResultPhaseName
  ) {
    throw new BestAgentError(
      "PROVIDER_DECISION_INVALID",
      "phase_result is allowed but phaseResultPhaseName is missing.",
    );
  }
  const allowPhaseResult =
    Boolean(controls.allowPhaseResult) &&
    actionPolicy.allowedActions.includes("phase_result");
  const allowPlanUpdate =
    Boolean(controls.allowPlanUpdate) &&
    actionPolicy.allowedActions.includes("plan_update");
  return {
    allowPhaseResult,
    allowPlanUpdate,
    ...(allowPhaseResult && controls.phaseResultPhaseName
      ? { phaseResultPhaseName: controls.phaseResultPhaseName }
      : {}),
  };
}
