import os
import uuid
from fastapi import HTTPException

async def transcription_service(file, model):
    if model is None:
        raise HTTPException(
            status_code=503,
            detail="Model is still loading, please try again in a moment."
        )

    file_location = f"temp_{uuid.uuid4()}_{file.filename}"

    try:
        # Save temp file
        with open(file_location, "wb") as f:
            f.write(await file.read())

        # AUTO LANGUAGE DETECTION
        # beam_size=1 = VERY FAST
        segments, info = model.transcribe(
            file_location,
            beam_size=10,
            best_of=10,
            vad_filter=True,
            language=None      # auto detect
        )

        # merge all segments
        text = " ".join([segment.text for segment in segments])
        clean_text = " ".join(text.split())

        return {
            "text": clean_text,
            "detected_language": info.language,
            "language_probability": round(info.language_probability, 3)
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        if os.path.exists(file_location):
            os.remove(file_location)
