"""笔记服务（笔记 CRUD + 日报）。
前端模式：请求 /api/notes/*，与网关 prefix /api/notes、rewritePrefix /api/v1/notes 对齐。
后端模式：直连 notes-service，请求 /api/v1/notes/*。
"""
from typing import Any, Optional

from .base_client import BaseClient
from .types import ClientConfig, RequestOptions, TokenStorage

_BACKEND_PREFIX = "/api/v1/notes"


class NotesService(BaseClient):
    service_path = "notes"

    def __init__(
        self,
        config: ClientConfig,
        token_storage: Optional[TokenStorage] = None,
    ) -> None:
        super().__init__(config, token_storage=token_storage)

    @property
    def service_name(self) -> str:
        return "notes"

    def _path_prefix(self) -> str:
        return "" if self.is_frontend_mode else _BACKEND_PREFIX

    # ==================== 笔记 ====================

    def create_note(
        self,
        request: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}",
            RequestOptions(method="POST", body=request),
        )

    def get_note(
        self,
        note_id: str,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/{note_id}",
            RequestOptions(method="GET"),
        )

    def update_note(
        self,
        note_id: str,
        request: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/{note_id}",
            RequestOptions(method="PUT", body=request),
        )

    def delete_note(
        self,
        note_id: str,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/{note_id}",
            RequestOptions(method="DELETE"),
        )

    def list_notes(
        self,
        params: Optional[dict] = None,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}",
            RequestOptions(method="GET", params=params or {}),
        )

    def search_notes(
        self,
        params: Optional[dict] = None,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/search",
            RequestOptions(method="GET", params=params or {}),
        )

    def append_to_note(
        self,
        note_id: str,
        request: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/{note_id}/append",
            RequestOptions(method="PATCH", body=request),
        )

    # ==================== 日报（子路径 /daily-reports） ====================

    def upsert_daily_report(
        self,
        date: str,
        request: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/daily-reports/{date}",
            RequestOptions(method="PUT", body=request),
        )

    def get_daily_report_by_date(
        self,
        date: str,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        try:
            return self.request(
                f"{self._path_prefix()}/daily-reports/{date}",
                RequestOptions(method="GET"),
            )
        except Exception as e:
            if hasattr(e, "response") and getattr(e.response, "status_code", None) == 404:
                return None
            raise

    def list_daily_reports(
        self,
        params: Optional[dict] = None,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/daily-reports",
            RequestOptions(method="GET", params=params or {}),
        )

    def delete_daily_report_by_date(
        self,
        date: str,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/daily-reports/{date}",
            RequestOptions(method="DELETE"),
        )

    def append_to_daily_report(
        self,
        date: str,
        request: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        return self.request(
            f"{self._path_prefix()}/daily-reports/{date}/append",
            RequestOptions(method="PATCH", body=request),
        )
