from __future__ import annotations

import re
from datetime import date
from http import HTTPStatus
from urllib.parse import parse_qs
from backend.data.providers.tushare_client import TushareError
from backend.features.market import ChartDataError


class MarketRoutesMixin:
    def _handle_market_get(self, parsed) -> bool:
        if parsed.path == "/api/dashboard":
            query = parse_qs(parsed.query)
            trade_date = query.get("trade_date", [date.today().isoformat()])[0]
            try:
                self.send_json(self.application_service.get_dashboard(trade_date, False))
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            except Exception as exc:
                self.send_json({"error": f"数据加载失败：{exc}"}, HTTPStatus.INTERNAL_SERVER_ERROR)
            return True
        if parsed.path == "/api/realtime-aggregate/health":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    {
                        "ok": True,
                        "aggregate": self.application_service.realtime_aggregate_health(
                            query.get("sector", [""])[0]
                        ),
                    }
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/search":
            query = parse_qs(parsed.query)
            search_query = query.get("q", [""])[0]
            trade_date = query.get("trade_date", [date.today().isoformat()])[0]
            try:
                self.send_json(self.application_service.search_entities(search_query, trade_date))
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/search/detail":
            query = parse_qs(parsed.query)
            entity_type = query.get("type", [""])[0]
            identifier = query.get("id", [""])[0]
            trade_date = query.get("trade_date", [date.today().isoformat()])[0]
            try:
                self.send_json(
                    self.application_service.get_search_detail(entity_type, identifier, trade_date)
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            except TushareError as exc:
                self.send_json({"error": f"行情加载失败：{exc}"}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/chart/intraday":
            query = parse_qs(parsed.query)
            entity_type = query.get("type", [""])[0]
            identifier = query.get("id", [""])[0]
            try:
                self.send_json(self.application_service.get_intraday_chart(entity_type, identifier))
            except (ValueError, ChartDataError) as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        stock_preview_match = re.fullmatch(r"/api/stock/(\d{6})/preview", parsed.path)
        if stock_preview_match:
            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_stock_preview(stock_preview_match.group(1), trade_date, force)
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        stock_match = re.fullmatch(r"/api/stock/(\d{6})", parsed.path)
        if stock_match:
            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_stock_detail(stock_match.group(1), trade_date, force))
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        return False
