// 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();

    if (extension === 'pdf') {
      // Create parser instance
    const parser = new PdfParse.SmartPDFParser({
       oversaturationFactor: 2.0,
      enableFastPath: true
      });
      console.log(`--- PDF Debug Start: ${filename} ---`);
      const result = await parser.parse(buffer);
      console.log(`Parsed ${result.numpages} pages using ${result._meta.method}`);
      console.log(`Parsed ${result.info} info using ${result._meta.method}`);
      console.log(`Parsed ${result.info} info using ${result._meta.method}`);
      console.log(JSON.stringify(result.info, null, 2));
      //const { text, numpages, info } = await pdf(buffer);
      //const parser = new PDFParse(buffer);
      // `text`   → full document text
      // `numpages` → page count
      // `info`  → metadata (author, creation date, etc.)

    // console.log(`Pages: ${numpages}`);
    // console.log(`Author: ${info.Author}`);
    // console.log(text.slice(0, 200)); // preview first 200 chars
        return {
          type: 'PDF',
          title: filename
        };
  }
}