import fs from "fs";
import { generateObject } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
import { ReceiptExtractionSchema } from "../src/lib/schema/receipt.ts";

const envContent = fs.readFileSync(".env.local", "utf-8");
const apiKeyMatch = envContent.match(/OPENROUTER_API_KEY=([^\r\n]+)/);
const apiKey = apiKeyMatch ? apiKeyMatch[1].trim() : "";

const demoImgPath = "public/demo/01_aral_tankbeleg_muenchen.jpg";
const imgBase64 = fs.readFileSync(demoImgPath).toString("base64");
const dataUrl = `data:image/jpeg;base64,${imgBase64}`;

async function testGpt5Models() {
  const models = ["openai/gpt-5-mini", "openai/gpt-5.4-mini", "openai/gpt-4o-mini"];
  const openrouter = createOpenAI({
    apiKey,
    baseURL: "https://openrouter.ai/api/v1",
  });

  for (const m of models) {
    console.log(`\nTesting ${m}...`);
    try {
      const { object } = await generateObject({
        model: openrouter(m),
        schema: ReceiptExtractionSchema,
        messages: [
          { role: "system", content: "Extrahiere den Beleg." },
          { role: "user", content: [{ type: "text", text: "Beleg:" }, { type: "image", image: dataUrl }] },
        ],
      });
      console.log(`✓ SUCCESS with ${m}! Merchant: ${object.merchant.name}, Total: ${object.totalAmount.value}`);
    } catch (err) {
      console.log(`✗ Error with ${m}:`, err.message);
    }
  }
}

testGpt5Models().catch(console.error);
