from fastapi import APIRouter, HTTPException, UploadFile, File, Form
from pydantic import BaseModel
from services.whisper_service import WhisperService

router = APIRouter(prefix="/transcribe", tags=["transcribe"])

ALLOWED_MIMES = {
    "audio/ogg", "audio/mpeg", "audio/wav", "audio/webm",
    "audio/aac", "audio/mp4", "video/mp4", "video/webm",
}
MAX_SIZE = 25 * 1024 * 1024  # 25 MB


class TranscribeResponse(BaseModel):
    text: str
    language: str
    segments: list[dict] = []


@router.post("/", response_model=TranscribeResponse)
async def transcribe_audio(
    file: UploadFile = File(...),
    language: str | None = Form(default=None),
):
    if file.content_type not in ALLOWED_MIMES:
        raise HTTPException(
            status_code=415,
            detail=f"Tip MIME nesupportat: {file.content_type}. Acceptat: {', '.join(ALLOWED_MIMES)}"
        )

    audio_bytes = await file.read()
    if len(audio_bytes) > MAX_SIZE:
        raise HTTPException(status_code=413, detail="Fișierul depășește limita de 25MB.")

    try:
        whisper = WhisperService()
        result  = await whisper.transcribe(audio_bytes, language=language)
        return TranscribeResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
