import fs from "fs";
import path from "path";
import { generateDualSheetExcel } from "./src/lib/export/excelGenerator.ts";
import { generateDatevCsv } from "./src/lib/export/csvGenerator.ts";
import { validateReceiptMath } from "./src/lib/ai/mathValidator.ts";
import { generateDeterministicDemoExtraction } from "./src/lib/ai/extractor.ts";

async function testPipeline() {
  console.log("=== 🧾 TESTING RECEIPT SCANNER PIPELINE ===");

  // 1. Test Demo Extraction
  const sample1 = generateDeterministicDemoExtraction("Aral_Tankstelle.jpg");
  console.log("✓ Sample Extraction Generated:", sample1.merchant.name, "Total:", sample1.totalAmount.value);

  // 2. Test Math Validation
  const mathValid = validateReceiptMath(sample1);
  console.log("✓ Math Validation Result (Valid case):", mathValid.isMathValid ? "VALID ✓" : "INVALID ✗");

  // Inconsistent case test
  const brokenSample = {
    ...sample1,
    totalAmount: { value: 100.0, confidence: 0.99 },
    netAmount: 50.0,
    taxBreakdown: [{ ratePercent: 19, taxAmount: 9.5, netAmount: 50.0 }],
  };
  const mathInvalid = validateReceiptMath(brokenSample);
  console.log("✓ Math Validation Discrepancy Detection (Discrepant case):", !mathInvalid.isMathValid ? "DETECTED AS EXPECTED ✓" : "FAILED ✗");

  // 3. Test Dual Sheet Excel Generation
  const testReceipts = [
    {
      ...sample1,
      id: "rcpt_test_1",
      imageHash: "hash_test_1",
      originalFileName: "Aral_Tankstelle.jpg",
      fileSizeBytes: 102400,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      status: "ready",
    },
    {
      ...generateDeterministicDemoExtraction("Trattoria_Bella_Vista.jpg"),
      id: "rcpt_test_2",
      imageHash: "hash_test_2",
      originalFileName: "Trattoria_Bella_Vista.jpg",
      fileSizeBytes: 204800,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      status: "ready",
    }
  ];

  const excelBuffer = await generateDualSheetExcel(testReceipts);
  console.log("✓ Dual-Sheet Excel (.xlsx) generated successfully. Size:", excelBuffer.length, "bytes");

  // 4. Test DATEV CSV Generation
  const datevCsv = generateDatevCsv(testReceipts);
  console.log("✓ DATEV CSV generated successfully. Starts with UTF-8 BOM:", datevCsv.startsWith("\uFEFF") ? "YES ✓" : "NO ✗");
  console.log("✓ Semicolon delimited count:", (datevCsv.match(/;/g) || []).length);

  console.log("=== ALL CORE PIPELINE TESTS PASSED SUCCESSFULLY! ===");
}

testPipeline().catch(err => {
  console.error("Test failed:", err);
  process.exit(1);
});
