import {File} from 'expo-file-system';
import {Audio} from 'react-native-compressor';
import api from '@config/api';
import {
  AttachmentType,
  FileAsset,
  UploadAssetType,
} from '@interfaces/attachments';
import {uploadAsset} from '@services/attachments';
import {isAndroid} from '@shared/utils';
import {ERROR} from '@shared/strings';

export interface HorusSummarizeResponse {
  transcript: string;
  summary: string;
  language_code: string;
  duration_seconds: number;
}

// react-native-compressor uses LAME natively on Android and crashes
// (SIGSEGV in L3psycho_anal_vbr); upload the recorded WAV as-is.
export const compressAudio = (uri: string): Promise<string> => {
  if (isAndroid) {
    return Promise.resolve(uri);
  }
  return Audio.compress(uri, {quality: 'medium'});
};

export const uploadAudioAsset = async (uri: string): Promise<FileAsset> => {
  const fileUri = isAndroid
    ? uri.startsWith('file://')
      ? uri
      : `file://${uri}`
    : uri.replace(/^file:\/\/\//, 'file://');
  const filename = fileUri.split('/').pop() ?? 'audio.mp4';
  const contentType = fileUri.toLowerCase().endsWith('.wav')
    ? 'audio/wav'
    : 'audio/mp4';
  const file = new File(fileUri);
  const size = file.size ?? 0;

  const result = await uploadAsset(
    {
      uri: fileUri,
      name: filename,
      type: contentType,
      sourceType: UploadAssetType.File,
      size,
    },
    AttachmentType.AUDIO,
  );

  if (result === ERROR || !result) {
    throw new Error('Failed to upload audio asset');
  }

  return result as FileAsset;
};

export const summarizeAudio = async (
  s3Key: string,
  contentType: string,
): Promise<HorusSummarizeResponse> => {
  const response = await api.post<HorusSummarizeResponse>(
    '/horus/ai/summarize',
    {
      s3_key: s3Key,
      content_type: contentType,
    },
    {
      withErrorBanner: false,
    },
  );

  if (!response.ok || !response.data) {
    throw new Error('Horus summarize request failed');
  }

  return response.data;
};
