# Generated by Gemini

import json
import os
import tempfile
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional

import uvicorn
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import JSONResponse
from orukeet import Orukeet

# Global dictionary/container to hold the pre-loaded model instance
app_state = {}


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 1. Load model ONCE during server startup
    config_path = Path("installation.json")
    if not config_path.is_file():
        raise FileNotFoundError(
            f"Installation file '{config_path}' not found. "
            "Run 'orukeet install' first to generate installation.json."
        )

    config = json.loads(config_path.read_text(encoding="utf-8-sig"))

    print(f"Loading Orukeet model ({config.get('device', 'cpu')})...")
    # Initialize Orukeet context manager and store the worker in state
    with Orukeet(config["model"], config["runtime"], device=config["device"]) as asr:
        app_state["asr"] = asr
        print("Orukeet model loaded successfully. Server ready!")
        yield  # Server runs here and handles requests

    # Cleanup when server shuts down
    app_state.clear()
    print("Orukeet model unloaded.")


app = FastAPI(title="Orukeet OpenAI-Compatible ASR Server", lifespan=lifespan)


@app.post("/v1/audio/transcriptions")
async def transcribe_audio(
    file: UploadFile = File(...),
    model: str = Form("orukeet"),
    language: Optional[str] = Form(None),
    response_format: Optional[str] = Form("json"),
):
    asr: Orukeet = app_state.get("asr")
    if not asr:
        raise HTTPException(status_code=503, detail="Orukeet model is not initialized.")

    # Preserve file extension if available (e.g., .wav, .mp3)
    suffix = Path(file.filename).suffix if file.filename else ".wav"

    # Save uploaded file to temporary location
    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
        temp_audio_path = Path(temp_file.name)
        contents = await file.read()
        temp_file.write(contents)

    try:
        # 2. Process file using the pre-loaded Orukeet model instance
        result = asr.transcribe(temp_audio_path)

        # Orukeet returns a dict, e.g. {"text": "..."} or structured result
        transcribed_text = result.get("text", "") if isinstance(result, dict) else str(result)

        # 3. Format response to match OpenAI's STT endpoint standards
        if response_format == "text":
            return transcribed_text

        return result

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")

    finally:
        # Cleanup temporary audio file
        if temp_audio_path.exists():
            os.remove(temp_audio_path)


if __name__ == "__main__":
    uvicorn.run("orukeet-server:app", host="0.0.0.0", port=8003, reload=False)
