"""Utility-model preference HTTP routes extracted from [mugi_backend._build_app](mugi_backend.py)."""
from __future__ import annotations

import asyncio
import logging
from typing import Any

from fastapi import Request as FRequest
from fastapi.responses import JSONResponse


def register_utility_model_preferences_routes(
    fastapi_app: Any,
    *,
    log: logging.Logger,
) -> None:
    """Register /preferences/utility_model/* routes."""

    @fastapi_app.get("/preferences/utility_model/status")
    async def utility_model_status_route():
        try:
            from utility_model import utility_model_status
            return JSONResponse(content=utility_model_status())
        except Exception as exc:
            from persistence import DEFAULT_UTILITY_MODEL_REPO
            return JSONResponse(content={
                "available": False,
                "loaded": False,
                "model_repo": DEFAULT_UTILITY_MODEL_REPO,
                "enabled": False,
                "utility_venv_installed": False,
                "prism_mlx_ready": False,
                "error": str(exc),
            })

    @fastapi_app.post("/preferences/utility_model/toggle")
    async def utility_model_toggle_route(request: FRequest):
        try:
            body = await request.json()
        except Exception:
            body = {}
        enabled = bool(body.get("enabled", True))
        try:
            from core import get_config, save_config
            config = get_config()
            config.setdefault("utility", {})["enabled"] = enabled
            save_config(config)
            if not enabled:
                try:
                    from utility_model import unload
                    unload()
                except Exception:
                    log.debug("Failed to unload utility model", exc_info=True)
            return JSONResponse(content={"ok": True, "enabled": enabled})
        except Exception as exc:
            return JSONResponse(content={"ok": False, "message": str(exc)}, status_code=500)

    @fastapi_app.post("/preferences/utility_model/unload")
    async def utility_model_unload_route():
        try:
            from utility_model import unload
            unload()
            return JSONResponse(content={"ok": True, "message": "Utility model unloaded."})
        except Exception as exc:
            return JSONResponse(content={"ok": False, "message": str(exc)}, status_code=500)

    @fastapi_app.post("/preferences/utility_model/set_model")
    async def utility_model_set_model_route(request: FRequest):
        try:
            body = await request.json()
        except Exception:
            body = {}
        model_repo = str(body.get("model_repo") or "").strip()
        if not model_repo:
            return JSONResponse(content={"ok": False, "message": "model_repo required"}, status_code=400)
        try:
            from core import get_config, save_config
            from utility_model import unload
            config = get_config()
            config.setdefault("utility", {})["model_repo"] = model_repo
            save_config(config)
            unload()
            return JSONResponse(content={"ok": True, "model_repo": model_repo})
        except Exception as exc:
            return JSONResponse(content={"ok": False, "message": str(exc)}, status_code=500)

    @fastapi_app.post("/preferences/utility_model/install")
    async def utility_model_install_route():
        try:
            from utility_model import ensure_downloaded
            loop = asyncio.get_event_loop()
            ok, msg = await loop.run_in_executor(None, ensure_downloaded)
            return JSONResponse(content={"ok": bool(ok), "message": str(msg or "")})
        except Exception as exc:
            return JSONResponse(content={"ok": False, "message": str(exc)}, status_code=500)

    @fastapi_app.post("/preferences/utility_model/upgrade_venv")
    async def utility_model_upgrade_venv_route():
        try:
            from app_mlx import upgrade_utility_mlx_venv
        except Exception:
            return JSONResponse(content={"ok": False, "message": "app_mlx not available"}, status_code=500)
        loop = asyncio.get_event_loop()
        try:
            ok, msg = await loop.run_in_executor(None, upgrade_utility_mlx_venv)
            return JSONResponse(content={"ok": bool(ok), "message": str(msg or "")})
        except Exception as exc:
            return JSONResponse(content={"ok": False, "message": str(exc)}, status_code=500)
