const BaseAgent = require('./BaseAgent');

class DocumentIntelligenceAgent extends BaseAgent {
    constructor() {
        super('DocumentIntelligenceAgent');
        this.responseMocks = {
            'default': JSON.stringify({
                documentType: 'LAB_REPORT',
                patientName: 'Jane Doe',
                date: '2026-05-26',
                metrics: [
                    { name: 'Fasting Blood Sugar', value: '110 mg/dL', status: 'BORDERLINE' },
                    { name: 'Total Cholesterol', value: '240 mg/dL', status: 'HIGH' }
                ],
                summary: 'Elevated cholesterol levels detected.'
            })
        };
    }

    async execute(config, payload) {
        const { documentUrl, documentTypeHint } = payload;
        
        console.log(`[DocumentIntelligenceAgent] Processing document image/pdf: ${documentUrl}`);
        
        const prompt = `
            Act as an expert medical document intelligence system. Analyze the provided image or PDF.
            Hint: This is likely a ${documentTypeHint}.
            Extract the document type, patient name, date, and key metrics/values. 
            Flag any metrics that are out of normal ranges.
            Return a JSON object: { "documentType": "...", "patientName": "...", "date": "...", "metrics": [{ "name", "value", "status" }], "summary": "..." }
        `;

        // Simulate sending image to Vision API
        const llmResponse = await this.mockLLMCall(prompt, this.responseMocks);
        
        try {
            const result = JSON.parse(llmResponse);
            console.log(`[DocumentIntelligenceAgent] Extracted ${result.metrics?.length || 0} metrics from ${result.documentType}.`);
            return result;
        } catch (e) {
            console.error('[DocumentIntelligenceAgent] Failed to parse Vision LLM response', e);
            return { documentType: 'UNKNOWN', metrics: [] };
        }
    }
}

module.exports = new DocumentIntelligenceAgent();
