from __future__ import annotations

import json
from datetime import date
from http import HTTPStatus
from urllib.parse import parse_qs
from backend.bootstrap.config import validate_text


class DragonTigerRoutesMixin:
    def _handle_dragon_tiger_get(self, parsed) -> bool:
        if parsed.path == "/api/dragon-tiger":
            query = parse_qs(parsed.query)
            trade_date = query.get("trade_date", [date.today().isoformat()])[0]
            force = query.get("force", ["0"])[0] == "1"
            try:
                self.send_json(self.application_service.get_dragon_tiger(trade_date, force))
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/dragon-tiger/profiles":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.get_hot_money_profiles(
                        query.get("force", ["0"])[0] == "1"
                    )
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/seat-aliases":
            self.send_json({"items": self.application_service.database.list_seat_aliases()})
            return True
        return False

    def save_seat_alias(self) -> None:
        try:
            body = self.read_json_body()
            seat_name = validate_text(body.get("seat_name"), "席位名称", 200, required=True)
            alias = validate_text(body.get("alias"), "席位别名", 50, required=True)
            self.application_service.database.save_seat_alias(seat_name, alias)
            self.send_json({"ok": True})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
