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 testLuna() {
  console.log("Testing openai/gpt-5.6-luna on OpenRouter...");

  const openrouter = createOpenAI({
    apiKey,
    baseURL: "https://openrouter.ai/api/v1",
    headers: {
      "HTTP-Referer": "http://localhost:3000",
      "X-Title": "Receipt Scanner to Excel",
    },
  });

  const { object } = await generateObject({
    model: openrouter("openai/gpt-5.6-luna"),
    schema: ReceiptExtractionSchema,
    messages: [
      {
        role: "system",
        content: "Du bist ein präziser Belegscanner. Extrahiere alle Daten im Schema.",
      },
      {
        role: "user",
        content: [
          { type: "text", text: "Extrahiere diesen Beleg vollständig:" },
          { type: "image", image: dataUrl },
        ],
      },
    ],
  });

  console.log("✓ SUCCESS WITH GPT-5.6-LUNA!");
  console.log("Extracted:", JSON.stringify(object, null, 2));
}

testLuna().catch(console.error);
