import argparse
import asyncio
import concurrent.futures
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 orukeet import Orukeet

app_state = {}


def parse_args():
    parser = argparse.ArgumentParser(description="Orukeet ASR Server")
    parser.add_argument(
        "--max-workers",
        type=int,
        default=None,
        help="Maximum concurrent transcription threads (defaults to total CPU logical cores)."
    )
    parser.add_argument("--port", type=int, default=8003, help="Port to run the server on (default: 8003).")
    parser.add_argument("--host", type=str, default="0.0.0.0", help="Host address to bind to (default: 0.0.0.0).")
    return parser.parse_args()


@asynccontextmanager
async def lifespan(app: FastAPI):
    max_workers = app_state.get("max_workers") or os.cpu_count() or 4
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
    app_state["executor"] = executor

    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 on {config.get('device', 'cpu')} with max_workers={max_workers}...")
    with Orukeet(config["model"], config["runtime"], device=config["device"]) as asr:
        app_state["asr"] = asr
        print("Orukeet model ready with segment timing support!")
        yield

    executor.shutdown(wait=True)
    app_state.clear()


app = FastAPI(title="Orukeet ASR Server with Segment Timings", lifespan=lifespan)


@app.post("/v1/audio/transcriptions")
async def transcribe_audio(
    file: UploadFile = File(...),
    model: str = Form("orukeet"),
    response_format: Optional[str] = Form("json"),
):
    asr: Orukeet = app_state.get("asr")
    executor: concurrent.futures.ThreadPoolExecutor = app_state.get("executor")

    if not asr or not executor:
        raise HTTPException(status_code=503, detail="Server model pool is not ready.")

    suffix = Path(file.filename).suffix if file.filename else ".wav"

    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
        temp_audio_path = Path(temp_file.name)
        temp_file.write(await file.read())

    try:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(executor, asr.transcribe, temp_audio_path)

        # 1. Plain text format
        if response_format == "text":
            return result.get("text", "")

        # 2. OpenAI verbose_json format (includes per-sentence/segment timing data)
        if response_format == "verbose_json":
            raw_segments = result.get("segments", [])

            formatted_segments = [
                {
                    "id": idx,
                    "start": seg.get("start", 0.0),
                    "end": seg.get("end", 0.0),
                    "text": seg.get("text", "").strip()
                }
                for idx, seg in enumerate(raw_segments)
            ]

            # Calculate total duration from last segment if not directly present in result
            duration = result.get("duration")
            if duration is None and formatted_segments:
                duration = formatted_segments[-1]["end"]

            return {
                "task": "transcribe",
                "language": result.get("language", "en"),
                "duration": duration or 0.0,
                "text": result.get("text", ""),
                "segments": formatted_segments
            }

        # 3. Standard JSON format
        return {"text": result.get("text", "")}

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

    finally:
        if temp_audio_path.exists():
            os.remove(temp_audio_path)


if __name__ == "__main__":
    args = parse_args()
    app_state["max_workers"] = args.max_workers
    uvicorn.run(app, host=args.host, port=args.port, reload=False)
