import {
  buildToolFollowUpSystemPrompt,
  stripRequiredToolSystemPrompt,
} from "../../prompt/runtime-prompts.js";
import type { CompletedProviderToolCall, ToolResumeContext } from "../checkpoint-codec.js";
import type { RequiredToolConstraint } from "./tool-constraint-types.js";

export function buildProviderToolFollowUpDecisionSystemPrompt(input: {
  completedToolCalls: CompletedProviderToolCall[];
  context: Pick<ToolResumeContext, "requiredToolConstraint" | "systemPrompt">;
  pendingToolHookContextPrompt?: string;
  unresolvedRequiredToolConstraint?: RequiredToolConstraint;
}): string | undefined {
  return mergeSystemPrompts(
    stripRequiredToolSystemPrompt(input.context.systemPrompt, input.context.requiredToolConstraint),
    buildToolFollowUpSystemPrompt(input.completedToolCalls),
    input.pendingToolHookContextPrompt,
  );
}

function mergeSystemPrompts(...parts: Array<string | undefined>): string | undefined {
  const content = parts
    .map((value) => value?.trim())
    .filter((value): value is string => Boolean(value && value.length > 0));
  if (content.length === 0) {
    return undefined;
  }
  return content.join("\n\n");
}
