from __future__ import annotations

import json
from http import HTTPStatus


class LLMHttpMixin:
    def save_llm_settings(self) -> None:
        try:
            body = self.read_json_body()
            service = self.application_service
            service.save_llm_settings(
                body.get("primary") or {},
                body.get("fallback") or {},
                bool(body.get("fallback_enabled")),
            )
            self.send_json(
                {
                    "ok": True,
                    "configured": service.llm_configured,
                    "model": service.llm_primary_model,
                    "fallback_configured": service.llm_fallback_configured,
                    "fallback_model": service.llm_fallback_model,
                }
            )
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

    def save_llm_mode(self) -> None:
        try:
            body = self.read_json_body()
            service = self.application_service
            service.save_llm_mode(str(body.get("mode") or "auto"))
            self.send_json({"ok": True, "llm_access": service.llm_access_status()})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

    def test_llm_settings(self) -> None:
        try:
            body = self.read_json_body()
            role = str(body.get("role") or "")
            profile = body.get("profile") or {}
            result = self.application_service.test_llm_profile(role, profile)
            self.send_json({"ok": True, "result": result})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
