from fastapi import HTTPException
import os
import tempfile
from botocore.exceptions import ClientError
from repositories import StorageRepository


class AudioService:
    def __init__(self, storage_repo: StorageRepository, bucket: str):
        self.storage_repo = storage_repo
        self.bucket = bucket

    def cleanup_tempfile(self, file_path: str) -> None:
        if os.path.exists(file_path):
            os.unlink(file_path)
            print(f"Cleaned up temp file: {file_path}")

    def get_audio_file(self, filename: str) -> str:
        try:
            # Add the audio/ prefix to match the MinIO structure
            minio_file_path = f"audio/{filename}"
            print(f"Attempting to download from MinIO: bucket={self.bucket}, path={minio_file_path}")
            
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
            self.storage_repo.download_file(self.bucket, minio_file_path, temp_file.name)
            temp_file.close()
            
            print(f"Successfully downloaded audio file: {minio_file_path}")
            return temp_file.name
            
        except ClientError as e:
            print(f"MinIO ClientError: {e}")
            print(f"Failed to find: bucket={self.bucket}, path=audio/{filename}")
            raise HTTPException(status_code=404, detail=f"Audio file '{filename}' not found.")
        except Exception as e:
            print(f"An error occurred: {e}")
            raise HTTPException(status_code=500, detail=f"An error occurred: {e}")