// src/lib/metadata-extractor.ts
// 1. Update your import to use the new named export
//import * as PDFLib from 'pdf-parse';
//import { PDFParse } from 'pdf-parse';
//import {pdf} from 'pdf-parse';
import * as PdfParse from 'pdf-parse-new';
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();

  try {
    // --- 1. PDF EXTRACTION (pdf-parse-new) ---
    if (extension === 'pdf') {
      const parser = new PdfParse.SmartPDFParser({
        oversaturationFactor: 2.0,
        enableFastPath: true
      });

      console.log(`--- PDF Extraction Start: ${filename} ---`);
      const result = await parser.parse(buffer);

      return {
        type: 'PDF',
        title: filename,
        // pageCount is specifically named 'numpages' in this library
        pageCount: result.numpages || 0,
        // We sanitize the result.info to handle those nested Custom objects
        details: sanitizeMetadata(result.info || {}),
        // Use result.text for a preview if available
        textPreview: result.text ? result.text.substring(0, 200).replace(/\s+/g, ' ') : ""
      };
    }

    // --- 2. IMAGE EXTRACTION ---
    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: any) {
    console.error(`❌ Extraction failed for ${filename}:`, error.message);
    return { type: 'FILE', title: filename, error: error.message };
  }
}