from __future__ import annotations

import json
from datetime import date
from http import HTTPStatus


class SystemHttpMixin:
    def save_system_settings(self) -> None:
        try:
            result = self.application_service.save_system_settings(self.read_json_body())
            self.send_json({"ok": True, **result})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

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

    def start_background_refresh(self) -> None:
        try:
            body = self.read_json_body(allow_empty=True)
            started = self.application_service.request_background_sync(
                str(body.get("trade_date") or date.today().isoformat())
            )
            self.send_json(
                {
                    "ok": True,
                    "started": started,
                    "message": "后台刷新已开始" if started else "已有后台刷新任务正在运行",
                },
                HTTPStatus.ACCEPTED,
            )
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
