from __future__ import annotations

from datetime import date
from http import HTTPStatus
from urllib.parse import parse_qs
from backend.data.providers.tushare_client import TushareError


class ThemeRoutesMixin:
    def _handle_themes_get(self, parsed) -> bool:
        if parsed.path == "/api/themes":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.theme_library(
                        query.get("trade_date", [date.today().isoformat()])[0],
                        query.get("force", ["0"])[0] == "1",
                    )
                )
            except (ValueError, TushareError) as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/themes/detail":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.theme_detail(
                        query.get("code", [""])[0],
                        query.get("trade_date", [date.today().isoformat()])[0],
                    )
                )
            except (ValueError, TushareError) as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        return False
