from __future__ import annotations

import re
from datetime import date
from http import HTTPStatus
from urllib.parse import parse_qs


class ReviewRoutesMixin:
    def _handle_review_get(self, parsed) -> bool:
        if parsed.path == "/api/trades":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.trade_entries(
                        query.get("start_date", [""])[0],
                        query.get("end_date", [""])[0],
                        query.get("code", [""])[0],
                    )
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/assistant/messages":
            self.send_json({"items": self.application_service.assistant_messages()})
            return True
        if parsed.path == "/api/watchlist":
            query = parse_qs(parsed.query)
            try:
                self.send_json(
                    self.application_service.review_watchlist(
                        query.get("trade_date", [date.today().isoformat()])[0]
                    )
                )
            except ValueError as exc:
                self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
            return True
        if parsed.path == "/api/notes":
            query = parse_qs(parsed.query)
            code = query.get("code", [""])[0]
            trade_date = query.get("trade_date", [""])[0].replace("-", "")
            scope = query.get("scope", ["all"])[0]
            if scope not in {"all", "daily", "stock"}:
                self.send_json({"error": "复盘记录范围不支持。"}, HTTPStatus.BAD_REQUEST)
                return True
            self.send_json(
                {
                    "items": self.application_service.database.list_notes(
                        self.application_service.current_user_id, code, trade_date, scope
                    )
                }
            )
            return True
        return False

    def _handle_review_delete(self, parsed) -> bool:
        if parsed.path == "/api/assistant/messages":
            deleted = self.application_service.clear_assistant_messages()
            self.send_json({"ok": True, "deleted": deleted})
            return True
        watchlist_match = re.fullmatch(r"/api/watchlist/(\d{6})", parsed.path)
        if watchlist_match:
            deleted = self.application_service.database.delete_watchlist(
                self.application_service.current_user_id, watchlist_match.group(1)
            )
            self.send_json({"ok": True, "deleted": deleted})
            return True
        note_match = re.fullmatch(r"/api/notes/(\d+)", parsed.path)
        if note_match:
            deleted = self.application_service.database.delete_note(
                self.application_service.current_user_id, int(note_match.group(1))
            )
            self.send_json({"ok": True, "deleted": deleted})
            return True
        trade_match = re.fullmatch(r"/api/trades/(\d+)", parsed.path)
        if trade_match:
            self.send_json(
                {"ok": True, **self.application_service.delete_trade_entry(int(trade_match.group(1)))}
            )
            return True
        return False
