// src/lib/metadata-extractor.ts
// 1. Update your import to use the new named export
import * as PDFLib from 'pdf-parse';
import sharp from 'sharp';
import exifReader from 'exif-reader';

/**
 * Converts EXIF DMS (Degrees, Minutes, Seconds) array to Decimal Degrees.
 */
function convertDMSToDD(dms: any, ref: string): string {
  if (!Array.isArray(dms) || dms.length < 3) return String(dms);
  
  const [degrees, minutes, seconds] = dms;
  let dd = degrees + (minutes / 60) + (seconds / 3600);

  if (ref === 'S' || ref === 'W') {
    dd = dd * -1;
  }
  return dd.toFixed(6);
}

/**
 * RECURSIVE SANITIZER:
 * Converts Buffers to strings, standardizes keys, and handles GPS conversion.
 */
function sanitizeMetadata(obj: any): any {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return obj.toISOString();
  if (Buffer.isBuffer(obj)) return `[Binary Data: ${obj.length} bytes]`;
  if (Array.isArray(obj)) return obj.map(sanitizeMetadata);

  const sanitized: any = {};
  for (const [key, value] of Object.entries(obj)) {
    const cleanKey = key.charAt(0).toLowerCase() + key.slice(1);

    // Specifically handle GPS Latitude/Longitude Arrays
    if (cleanKey === 'gPSLatitude' && obj['gPSLatitudeRef']) {
      sanitized[cleanKey] = convertDMSToDD(value, obj['gPSLatitudeRef']);
      continue;
    }
    if (cleanKey === 'gPSLongitude' && obj['gPSLongitudeRef']) {
      sanitized[cleanKey] = convertDMSToDD(value, obj['gPSLongitudeRef']);
      continue;
    }

    sanitized[cleanKey] = sanitizeMetadata(value);
  }
  return sanitized;
}

export async function extractMetadata(buffer: Buffer, filename: string): Promise<any> {
  const extension = filename.split('.').pop()?.toLowerCase();

  if (extension === 'pdf') {
    console.log(`--- PDF Debug Start: ${filename} ---`);
    
    // Initialize using the data property for our Buffer
    const parser = new PDFLib.PDFParse({ 
      data: buffer,
      // disableWorker: true, // Crucial for Next.js
      // verbosity: 0 
    });

    try {
      const result = await parser.getInfo({ parsePageInfo: true });
      
      // LOGGING TO TERMINAL
      console.log(`✅ Total pages: ${result.total}`);
      console.log(`✅ Title: ${result.info?.Title}`);
      console.log(`✅ Author: ${result.info?.Author}`);
      console.log(`✅ Creator: ${result.info?.Creator}`);
      
      // Date info
      const dates = result.getDateNode();
      console.log(`✅ Creation Date: ${dates.CreationDate}`);

      console.log('--- PDF Debug End ---');
    }
      // return {
      //   type: 'PDF',
      //   title: filename,
      //   pageCount: result.total,
      //   details: result.info, // This sends the raw info object back
      // };
    // } catch (err: any) {
    //   console.error("❌ PDF Parsing Error inside debug block:", err.message);
    //   return { type: 'PDF', error: err.message };
    // } finally {
    //   await parser.destroy();
    // }
  
    // --- 1. PDF EXTRACTION (v2 Class-based) ---
    // if (extension === 'pdf') {
    //   // Access PDFParse from the namespace
    //   const parser = new PDFLib.PDFParse({ 
    //     data: buffer,
    //     disableWorker: true, // Prevents the .mjs worker error
    //     verbosity: 0 
    //   });

    //   try {
    //     const infoResult = await parser.getInfo({ parsePageInfo: true });
    //     const textResult = await parser.getText();

    //     return {
    //       type: 'PDF',
    //       title: filename,
    //       details: sanitizeMetadata(infoResult.info || {}),
    //       pageCount: infoResult.total || 0,
    //       textPreview: textResult.text ? textResult.text.substring(0, 200).replace(/\s+/g, ' ') : ""
    //     };
    //   } finally {
    //     // Free memory
    //     await parser.destroy();
    //   }
    // }
  
    if (['jpg', 'jpeg', 'png', 'webp'].includes(extension || '')) {
      const image = sharp(buffer);
      const metadata = await image.metadata();
      
      let details = {};
      if (metadata.exif) {
        try {
          const rawExif = exifReader(metadata.exif);
          details = sanitizeMetadata(rawExif);
        } catch (e) {
          console.warn("EXIF Parse failed");
        }
      }

      return {
        type: `IMAGE (${metadata.format?.toUpperCase()})`,
        dimensions: `${metadata.width}x${metadata.height}`,
        title: filename,
        details: details 
      };
    }

    return { type: 'FILE', title: filename };
  } catch (error) {
    console.error(`Extraction failed: ${filename}`, error);
    return { type: 'FILE', title: filename, error: "Extraction failed" };
  }
}