from __future__ import annotations

import json
from http import HTTPStatus

from backend.features.heaven.knowledge import HeavenKnowledgeError


class HeavenHttpMixin:
    def _send_heaven_client_error(self, exc: Exception) -> None:
        payload: dict = {"error": str(exc)}
        code = getattr(exc, "error_code", None)
        if code:
            payload["code"] = str(code)
        self.send_json(payload, HTTPStatus.BAD_REQUEST)

    def heaven_hexagram(self) -> None:
        try:
            body = self.read_json_body()
            result = self.application_service.heaven_hexagram(body.get("lines"))
            self.send_json({"ok": True, "hexagram": result})
        except (ValueError, json.JSONDecodeError) as exc:
            self._send_heaven_client_error(exc)

    def heaven_personal(self) -> None:
        try:
            body = self.read_json_body()
            result = self.application_service.heaven_personal(body)
            self.send_json({"ok": True, "personal": result})
        except (ValueError, json.JSONDecodeError) as exc:
            self._send_heaven_client_error(exc)

    def heaven_interpret(self) -> None:
        try:
            body = self.read_json_body()
            result = self.application_service.heaven_interpret(body)
            self.send_json({"ok": True, **result})
        except (HeavenKnowledgeError, ValueError, json.JSONDecodeError) as exc:
            self._send_heaven_client_error(exc)
