/**
 * PDF detection system
 * Detects PDF downloads using Chrome Downloads API
 */

export interface DetectedPDF {
  id: string; // unique identifier
  filename: string;
  url: string; // original URL
  size: number; // bytes
  timestamp: number; // detection time
  sourceDomain: string; // domain where PDF originated
}

/**
 * Check if a download item is a PDF
 */
function isPDF(item: chrome.downloads.DownloadItem): boolean {
  // Check file extension
  if (item.filename.toLowerCase().endsWith('.pdf')) {
    return true;
  }

  // Check MIME type
  if (item.mime === 'application/pdf') {
    return true;
  }

  return false;
}

/**
 * Extract domain from URL
 */
function extractDomain(url: string): string {
  try {
    const urlObj = new URL(url);
    return urlObj.hostname;
  } catch {
    return 'unknown';
  }
}

/**
 * Convert download item to DetectedPDF
 */
function downloadItemToPDF(item: chrome.downloads.DownloadItem): DetectedPDF {
  return {
    id: `download-${item.id}`,
    filename: item.filename.split('/').pop() || item.filename,
    url: item.url,
    size: item.fileSize,
    timestamp: Date.now(),
    sourceDomain: extractDomain(item.url)
  };
}

/**
 * Start listening for PDF downloads
 */
export function startPDFDetection(
  onPDFDetected: (pdf: DetectedPDF) => void
): void {
  console.log('[PDF Detector] Starting PDF detection, registering download listener');

  // Listen for download changes
  chrome.downloads.onChanged.addListener((delta) => {
    console.log('[PDF Detector] Download changed:', {
      id: delta.id,
      state: delta.state,
      stateValue: delta.state?.current
    });

    // Only process completed downloads
    if (delta.state?.current !== 'complete') {
      console.log('[PDF Detector] Download not complete, ignoring');
      return;
    }

    console.log('[PDF Detector] Download complete, searching for item:', delta.id);

    // Get full download item details
    chrome.downloads.search({ id: delta.id }, (items) => {
      console.log('[PDF Detector] Search results:', items.length, 'items');

      if (items.length === 0) {
        console.warn('[PDF Detector] No items found for download ID:', delta.id);
        return;
      }

      const item = items[0];
      console.log('[PDF Detector] Download item:', {
        id: item.id,
        filename: item.filename,
        mime: item.mime,
        state: item.state,
        url: item.url
      });

      if (isPDF(item)) {
        console.log('[PDF Detector] PDF detected!');
        const pdf = downloadItemToPDF(item);
        onPDFDetected(pdf);
      } else {
        console.log('[PDF Detector] Not a PDF, ignoring');
      }
    });
  });

  console.log('[PDF Detector] Listener registered successfully');
}

/**
 * Get the most recent PDF download
 */
export async function getLastPDFDownload(): Promise<DetectedPDF | null> {
  return new Promise((resolve) => {
    chrome.downloads.search(
      {
        limit: 100, // check last 100 downloads
        orderBy: ['-startTime']
      },
      (items) => {
        const pdfItem = items.find(isPDF);
        if (pdfItem && pdfItem.state === 'complete') {
          resolve(downloadItemToPDF(pdfItem));
        } else {
          resolve(null);
        }
      }
    );
  });
}

/**
 * Fetch PDF bytes from original URL
 * Uses the user's session cookies automatically
 */
export async function fetchPDFBytes(url: string): Promise<ArrayBuffer> {
  const response = await fetch(url, {
    credentials: 'include' // include cookies
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch PDF: ${response.status} ${response.statusText}`);
  }

  const contentType = response.headers.get('Content-Type');
  if (contentType && !contentType.includes('application/pdf')) {
    throw new Error(`URL did not return a PDF (got ${contentType})`);
  }

  return await response.arrayBuffer();
}
