"""
Watchlist resource — ticker state, impacts, sparklines, CRUD.
"""
from typing import Any, Dict, List, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from kronical.client import KronicalClient, AsyncKronicalClient


class WatchlistResource:
    """Synchronous watchlist methods."""

    def __init__(self, client: "KronicalClient"):
        self._client = client

    # --- Ticker data (read-only) ---

    def ticker_states(self, tickers: List[str]) -> Dict[str, Any]:
        """
        GET /v1/watchlist/tickers — cached state-of-play for multiple tickers.

        Args:
            tickers: List of ticker symbols (e.g. ["AAPL", "NVDA"]).

        Returns:
            {"tickers": [...], "count": int}
        """
        return self._client.request("GET", "/v1/watchlist/tickers", params={
            "tickers": ",".join(tickers),
        })

    def ticker_state(self, ticker: str) -> Dict[str, Any]:
        """
        GET /v1/watchlist/ticker/{ticker} — full state for a single ticker.
        """
        return self._client.request("GET", f"/v1/watchlist/ticker/{ticker}")

    def sparkline(self, ticker: str) -> Dict[str, Any]:
        """
        GET /v1/watchlist/ticker/{ticker}/sparkline — 24h hourly close prices.

        Returns:
            {"ticker": str, "data": [{"time": float, "close": float}], "count": int}
        """
        return self._client.request("GET", f"/v1/watchlist/ticker/{ticker}/sparkline")

    def impacts(self, ticker: str, *, hours: int = 24) -> Dict[str, Any]:
        """
        GET /v1/watchlist/ticker/{ticker}/impacts — shift-headline impacts.

        Returns:
            {"ticker": str, "impacts": [...], "hours": int}
        """
        return self._client.request("GET", f"/v1/watchlist/ticker/{ticker}/impacts", params={
            "hours": hours,
        })

    def multi_impacts(self, tickers: List[str], *, hours: int = 24) -> Dict[str, Any]:
        """
        GET /v1/watchlist/impacts — impacts for multiple tickers at once.
        """
        return self._client.request("GET", "/v1/watchlist/impacts", params={
            "tickers": ",".join(tickers),
            "hours": hours,
        })

    def search_tickers(self, query: str, *, limit: int = 15) -> Dict[str, Any]:
        """
        GET /v1/watchlist/tickers/search — search ticker universe.
        """
        return self._client.request("GET", "/v1/watchlist/tickers/search", params={
            "q": query,
            "limit": limit,
        })

    # --- Watchlist CRUD ---

    def create(self, name: str, tickers: List[str]) -> Dict[str, Any]:
        """
        POST /v1/watchlist/watchlists — create a new watchlist.
        """
        return self._client.request("POST", "/v1/watchlist/watchlists", json={
            "name": name,
            "tickers": tickers,
        })

    def list(self) -> Dict[str, Any]:
        """
        GET /v1/watchlist/watchlists — list all watchlists.
        """
        return self._client.request("GET", "/v1/watchlist/watchlists")

    def update(
        self,
        watchlist_id: str,
        *,
        name: Optional[str] = None,
        tickers: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        """
        PUT /v1/watchlist/watchlists/{id} — update a watchlist.
        """
        body: Dict[str, Any] = {}
        if name is not None:
            body["name"] = name
        if tickers is not None:
            body["tickers"] = tickers
        return self._client.request("PUT", f"/v1/watchlist/watchlists/{watchlist_id}", json=body)

    def delete(self, watchlist_id: str) -> Dict[str, Any]:
        """
        DELETE /v1/watchlist/watchlists/{id} — delete a watchlist.
        """
        return self._client.request("DELETE", f"/v1/watchlist/watchlists/{watchlist_id}")


class AsyncWatchlistResource:
    """Asynchronous watchlist methods."""

    def __init__(self, client: "AsyncKronicalClient"):
        self._client = client

    async def ticker_states(self, tickers: List[str]) -> Dict[str, Any]:
        """GET /v1/watchlist/tickers — cached state for multiple tickers."""
        return await self._client.request("GET", "/v1/watchlist/tickers", params={
            "tickers": ",".join(tickers),
        })

    async def ticker_state(self, ticker: str) -> Dict[str, Any]:
        """GET /v1/watchlist/ticker/{ticker} — single ticker state."""
        return await self._client.request("GET", f"/v1/watchlist/ticker/{ticker}")

    async def sparkline(self, ticker: str) -> Dict[str, Any]:
        """GET /v1/watchlist/ticker/{ticker}/sparkline — 24h prices."""
        return await self._client.request("GET", f"/v1/watchlist/ticker/{ticker}/sparkline")

    async def impacts(self, ticker: str, *, hours: int = 24) -> Dict[str, Any]:
        """GET /v1/watchlist/ticker/{ticker}/impacts — shift impacts."""
        return await self._client.request("GET", f"/v1/watchlist/ticker/{ticker}/impacts", params={
            "hours": hours,
        })

    async def multi_impacts(self, tickers: List[str], *, hours: int = 24) -> Dict[str, Any]:
        """GET /v1/watchlist/impacts — multi-ticker impacts."""
        return await self._client.request("GET", "/v1/watchlist/impacts", params={
            "tickers": ",".join(tickers),
            "hours": hours,
        })

    async def search_tickers(self, query: str, *, limit: int = 15) -> Dict[str, Any]:
        """GET /v1/watchlist/tickers/search — search tickers."""
        return await self._client.request("GET", "/v1/watchlist/tickers/search", params={
            "q": query,
            "limit": limit,
        })

    async def create(self, name: str, tickers: List[str]) -> Dict[str, Any]:
        """POST /v1/watchlist/watchlists — create watchlist."""
        return await self._client.request("POST", "/v1/watchlist/watchlists", json={
            "name": name,
            "tickers": tickers,
        })

    async def list(self) -> Dict[str, Any]:
        """GET /v1/watchlist/watchlists — list watchlists."""
        return await self._client.request("GET", "/v1/watchlist/watchlists")

    async def update(
        self,
        watchlist_id: str,
        *,
        name: Optional[str] = None,
        tickers: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        """PUT /v1/watchlist/watchlists/{id} — update watchlist."""
        body: Dict[str, Any] = {}
        if name is not None:
            body["name"] = name
        if tickers is not None:
            body["tickers"] = tickers
        return await self._client.request("PUT", f"/v1/watchlist/watchlists/{watchlist_id}", json=body)

    async def delete(self, watchlist_id: str) -> Dict[str, Any]:
        """DELETE /v1/watchlist/watchlists/{id} — delete watchlist."""
        return await self._client.request("DELETE", f"/v1/watchlist/watchlists/{watchlist_id}")
