import { createLlmClient } from "../core/llm-client.ts";
import {
  getRequiredPayloadString,
  renderPromptTemplate,
  resolvePromptBundle,
} from "../internal/prompt-runtime.js";

import {
  buildProcurementListExtractionRequest,
  buildProcurementListExtractionPromptVariables,
  parseProcurementListExtractionPayload,
  type BuildProcurementListExtractionRequestInput,
  type ProcurementListExtractionPayload,
} from "./procurement-extraction-contract.ts";

const PROCUREMENT_LIST_EXTRACTION_PROMPT_KEY = "automation.procurement_list.extraction.bundle";

export type ExtractProcurementListFromMultimodalInputsInput = Omit<
  BuildProcurementListExtractionRequestInput,
  "model" | "systemPrompt" | "userPrompt"
>;

export interface ExtractProcurementListFromMultimodalInputsResult {
  payload: ProcurementListExtractionPayload;
  model: string;
  provider: string;
}

export async function extractProcurementListFromMultimodalInputs(
  input: ExtractProcurementListFromMultimodalInputsInput,
): Promise<ExtractProcurementListFromMultimodalInputsResult> {
  const { client, config } = await createLlmClient({ maxRetries: 2, stage: "document_extraction" });
  const promptBundle = await resolvePromptBundle(PROCUREMENT_LIST_EXTRACTION_PROMPT_KEY, {
    provider: config.provider || process.env.PROMPT_PROVIDER || "*",
    model: config.model || "*",
    expectedContentFormat: "multimodal_bundle",
  });
  const userTemplate = getRequiredPayloadString(promptBundle, "user_template");
  const request = buildProcurementListExtractionRequest({
    ...input,
    model: config.model,
    systemPrompt: getRequiredPayloadString(promptBundle, "system"),
    userPrompt: renderPromptTemplate(
      userTemplate,
      buildProcurementListExtractionPromptVariables(input),
    ),
  });
  const response = await client.chat.completions.create(request as never);
  const content = response.choices[0]?.message?.content ?? "";

  if (!content.trim()) {
    throw new Error("采购清单多模态模型返回内容为空");
  }

  return {
    payload: parseProcurementListExtractionPayload(content),
    model: config.model,
    provider: config.provider,
  };
}
