import { createLlmClient } from "../core/llm-client.ts";

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

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

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 request = buildProcurementListExtractionRequest({
    ...input,
    model: config.model,
  });
  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,
  };
}
