import { Logger } from '@nestjs/common';
import * as pdfParse from 'pdf-parse';
import { createWorker } from 'tesseract.js';
import { RecipeParser, ParsedRecipe } from './base.parser';

interface ParsedReceiptItem {
  name: string;
  quantity: number;
  price: number;
}

export class ReceiptParser extends RecipeParser {
  private readonly logger = new Logger(ReceiptParser.name);

  canHandle(url: string): boolean {
    // This parser is for receipts, not URLs, so it will be used directly in the service
    return false;
  }

  async parseFromPdf(buffer: Buffer): Promise<ParsedReceiptItem[]> {
    try {
      this.logger.log('Parsing PDF receipt...');
      const data = await pdfParse(buffer);
      const text = data.text;
      return this.parseReceiptText(text);
    } catch (error) {
      this.logger.error('Failed to parse PDF receipt', error);
      throw new Error('Failed to parse PDF receipt');
    }
  }

  async parseFromImage(buffer: Buffer): Promise<ParsedReceiptItem[]> {
    try {
      this.logger.log('Parsing image receipt...');
      const worker = await createWorker('eng');
      const ret = await worker.recognize(buffer);
      await worker.terminate();
      const text = ret.data.text;
      return this.parseReceiptText(text);
    } catch (error) {
      this.logger.error('Failed to parse image receipt', error);
      throw new Error('Failed to parse image receipt');
    }
  }

  parseReceiptText(text: string): ParsedReceiptItem[] {
    this.logger.log('Parsing receipt text...');
    // Simple parsing logic to extract items from receipt text
    // This is a placeholder and should be replaced with actual parsing logic
    const lines = text.split('\n');
    const items: ParsedReceiptItem[] = [];
    
    for (const line of lines) {
      if (line.trim() === '') continue;
      // Example parsing logic: "2x Apple 10.00 SEK"
      const match = line.match(/(\d+)x\s+(.+?)\s+([\d.]+)\s*SEK/);
      if (match) {
        const quantity = parseInt(match[1], 10);
        const name = match[2].trim();
        const price = parseFloat(match[3]);
        items.push({ name, quantity, price });
      }
    }
    
    return items;
  }
}