import { UploadedFile } from '../types';

export const processFile = async (file: File): Promise<UploadedFile> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = (e) => {
      const result = e.target?.result as string;
      
      // Determine simplified MIME type for Gemini
      let mimeType = file.type;
      
      // Handle GPX explicitly as text if the browser doesn't detect it perfectly
      if (file.name.toLowerCase().endsWith('.gpx')) {
        mimeType = 'text/plain'; // Treat GPX as text for the prompt
      } else if (file.name.toLowerCase().endsWith('.pdf')) {
        mimeType = 'application/pdf';
      }

      // Extract base64 data if it's an image or PDF
      let content = result;
      if (result.includes('base64,')) {
         content = result.split('base64,')[1];
      }

      resolve({
        id: crypto.randomUUID(),
        file,
        previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined,
        content: content,
        mimeType: mimeType
      });
    };

    reader.onerror = () => reject(new Error('Error reading file'));

    if (file.name.toLowerCase().endsWith('.gpx')) {
        reader.readAsText(file); // Read GPX as text
    } else {
        reader.readAsDataURL(file); // Read Images/PDFs as Base64
    }
  });
};