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

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

MAX_SIZE = 100 * 1024 * 1024  # 100 MB


class CaptionSegment(BaseModel):
    start: float
    end: float
    text: str


class CaptionResponse(BaseModel):
    language: str
    segments: list[CaptionSegment]
    full_text: str


@router.post("/", response_model=CaptionResponse)
async def generate_captions(
    file: UploadFile = File(...),
    language: str | None = Form(default=None),
):
    video_bytes = await file.read()
    if len(video_bytes) > MAX_SIZE:
        raise HTTPException(status_code=413, detail="Video depășește 100MB.")

    try:
        whisper  = WhisperService()
        result   = await whisper.transcribe(video_bytes, language=language)
        segments = [CaptionSegment(**s) for s in result.get("segments", [])]
        return CaptionResponse(
            language=result["language"],
            segments=segments,
            full_text=result["text"],
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Caption generation failed: {str(e)}")
