import * as pdf from 'pdf-parse';
import EPub from 'epub';
import sharp from 'sharp';
import exifReader from 'exif-reader';

export interface ExtractedMetadata {
  title?: string;
  author?: string;
  subject?: string;
  dimensions?: string;
  pageCount?: number;
  latitude?: number;
  longitude?: number;
  type: string;
}

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

  try {
    // --- 1. PDF EXTRACTION ---
   if (extension === 'pdf') {
      // Use any to bypass the missing 'default' property error in ESM
      const parsePdf = (pdf as any).default || pdf;
      const data = await parsePdf(buffer);
      
      return {
        type: 'PDF',
        title: data.info?.Title || filename,
        author: data.info?.Author,
        subject: data.info?.Subject,
        pageCount: data.numpages,
      };
    }

    // --- 2. EPUB EXTRACTION ---
    if (extension === 'epub') {
      // Logic for EPub usually requires file path or custom stream handler
      // Keeping placeholder for your existing EPub logic
      return { type: 'EPUB', title: filename };
    }

    // --- 3. IMAGE EXTRACTION (Enhanced with GPS) ---
    if (['jpg', 'jpeg', 'png', 'webp'].includes(extension || '')) {
      const image = sharp(buffer);
      const metadata = await image.metadata();
      
      let gps: { latitude?: number; longitude?: number } = {};

      if (metadata.exif) {
        try {
          // Cast to any to bypass strict Exif type checking for nested GPS properties
          const exif = exifReader(metadata.exif) as any;
          
          // Debugging log to see the raw structure in your terminal
          console.log("📸 FULL RAW EXIF DATA:", JSON.stringify(exif, null, 2));

          if (exif.gps && exif.gps.GPSLatitude && exif.gps.GPSLongitude) {
            // EXIF stores GPS as [Degrees, Minutes, Seconds]
            // We convert to Decimal Degrees for Google Maps
            const lat = exif.gps.GPSLatitude;
            const lon = exif.gps.GPSLongitude;

            let latitude = lat[0] + lat[1] / 60 + lat[2] / 3600;
            let longitude = lon[0] + lon[1] / 60 + lon[2] / 3600;

            // Adjust for South or West hemisphere
            if (exif.gps.GPSLatitudeRef === 'S') latitude *= -1;
            if (exif.gps.GPSLongitudeRef === 'W') longitude *= -1;

            gps.latitude = latitude;
            gps.longitude = longitude;
          }
        } catch (exifError) {
          console.warn("Could not parse EXIF data for:", filename, exifError);
        }
      }

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

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