import { tap, expect } from '@git.zone/tstest/tapbundle';
import * as qenv from '@push.rocks/qenv';
import { getModel } from '../ts/index.js';
import { analyzeDocuments, stopSmartpdf } from '../ts_document/index.js';

const testQenv = new qenv.Qenv('./', './.nogit/');

tap.test('analyzeDocuments should analyze a PDF', async () => {
  const apiKey = await testQenv.getEnvVarOnDemand('ANTHROPIC_TOKEN');
  if (!apiKey) {
    console.log('ANTHROPIC_TOKEN not set, skipping test');
    return;
  }

  // Create a minimal test PDF (this is a valid minimal PDF)
  const minimalPdf = Buffer.from(
    '%PDF-1.0\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n' +
    '2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n' +
    '3 0 obj<</Type/Page/MediaBox[0 0 612 792]/Parent 2 0 R/Contents 4 0 R/Resources<</Font<</F1 5 0 R>>>>>>endobj\n' +
    '4 0 obj<</Length 44>>stream\nBT /F1 12 Tf 100 700 Td (Hello World) Tj ET\nendstream\nendobj\n' +
    '5 0 obj<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>endobj\n' +
    'xref\n0 6\n0000000000 65535 f \n0000000009 00000 n \n0000000058 00000 n \n0000000115 00000 n \n0000000266 00000 n \n0000000360 00000 n \n' +
    'trailer<</Size 6/Root 1 0 R>>\nstartxref\n434\n%%EOF'
  );

  const model = getModel({
    provider: 'anthropic',
    model: 'claude-sonnet-4-5-20250929',
    apiKey,
    promptCaching: false,
  });

  try {
    const result = await analyzeDocuments({
      model,
      systemMessage: 'You are a document analysis assistant.',
      userMessage: 'What text is visible in this document?',
      pdfDocuments: [minimalPdf],
    });

    console.log('Document analysis result:', result);
    expect(result).toBeTruthy();
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.log('Document test failed (may need puppeteer):', message);
  } finally {
    await stopSmartpdf();
  }
});

export default tap.start();
