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:
            temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
            self.storage_repo.download_file(self.bucket, filename, temp_file.name)
            temp_file.close()
            return temp_file.name
        except ClientError as e:
            print(f"MinIO ClientError: {e}")
            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}")

