import * as OriginalFileSystem from 'expo-file-system/legacy';
import { addTelemetryEvent } from './telemetry';

const wrappedDownloadAsync = async function (
  url: string,
  fileUri: string,
  options?: any
): Promise<any> {
  const start = Date.now();
  try {
    const result = await OriginalFileSystem.downloadAsync(url, fileUri, options);
    const duration = Date.now() - start;

    let fileSize = 0;
    try {
      const info = await OriginalFileSystem.getInfoAsync(fileUri);
      if (info.exists) {
        fileSize = info.size || 0;
      }
    } catch {}

    let caller = 'File Download';
    const lowerUrl = url.toLowerCase();
    if (lowerUrl.includes('.db')) {
      caller = 'Database Update (.db)';
    } else if (lowerUrl.includes('/flags/')) {
      caller = 'Flags Download';
    } else if (lowerUrl.includes('map')) {
      caller = 'Map Details';
    } else if (lowerUrl.includes('chat') || lowerUrl.includes('message')) {
      caller = 'Chat & Messages';
    }

    addTelemetryEvent({
      type: 'file_download',
      url,
      caller,
      reqSize: 0,
      resSize: fileSize,
      status: 200,
      duration
    });

    return result;
  } catch (error: any) {
    const duration = Date.now() - start;
    let caller = 'File Download (Failed)';
    const lowerUrl = url.toLowerCase();
    if (lowerUrl.includes('.db')) {
      caller = 'Database Update (Failed)';
    }

    addTelemetryEvent({
      type: 'file_download',
      url,
      caller,
      reqSize: 0,
      resSize: 0,
      status: error.status || 500,
      duration
    });
    throw error;
  }
};

export const FileSystem = new Proxy(OriginalFileSystem, {
  get(target, prop, receiver) {
    if (prop === 'downloadAsync') {
      return wrappedDownloadAsync;
    }
    return Reflect.get(target, prop, receiver);
  }
}) as typeof OriginalFileSystem;
