import type { RunPhaseName, WorkflowName, WorkflowPhaseName } from "@best-agent/protocol";

export function initialAdvancedPhaseForProfileName(
  profileName: string,
): Exclude<RunPhaseName, "wait"> {
  if (profileName === "plan") {
    return "plan";
  }
  return profileName === "verify" ? "verify" : "inspect";
}

export function buildWorkflowPhaseInstruction(
  workflowName: WorkflowName,
  phaseName: WorkflowPhaseName,
): string {
  return [
    `Workflow phase context: executing the ${phaseName} phase of the ${workflowName} workflow.`,
    "Allowed runtime actions: tool, phase_result.",
    phaseName === "verify"
      ? "Runtime contract: choose any valid action from the allowed action set using current context and evidence."
      : "Runtime contract: choose any valid action from the allowed action set using current context.",
    "Runtime contract: structured decisions must use the runtime-provided format for this turn.",
    "The response must be one valid structured decision.",
  ].join("\n");
}

export function buildAdvancedPhaseInstruction(phaseName: Exclude<RunPhaseName, "wait">): string {
  switch (phaseName) {
    case "inspect":
      return structuredPhaseInstruction("inspect", "phase_result");
    case "plan":
      return structuredPhaseInstruction("plan", "plan_update");
    case "change":
      return structuredPhaseInstruction("change", "phase_result");
    case "verify":
      return structuredPhaseInstruction("verify", "phase_result", true);
    case "summarize":
      return [
        "You are in the summarize phase of an advanced run.",
        "Runtime contract: provide the final user-facing answer.",
        "Internal phase labels and tool narration are not part of the user-facing answer.",
      ].join("\n");
  }
}

function structuredPhaseInstruction(
  phaseName: Exclude<RunPhaseName, "summarize" | "wait">,
  completionAction: "phase_result" | "plan_update",
  includeEvidence = false,
): string {
  return [
    `Phase context: ${phaseName} phase of an advanced run.`,
    `Allowed runtime actions: tool, ${completionAction}.`,
    includeEvidence
      ? "Runtime contract: choose any valid action from the allowed action set using current context and evidence."
      : "Runtime contract: choose any valid action from the allowed action set using current context.",
    "Runtime contract: structured decisions must use the runtime-provided format for this turn.",
    "The response must be one valid structured decision.",
  ].join("\n");
}
