"""StationMonster SDK for Python 3.8+ (standard library only).

    from stationmonster import StationMonster
    sm = StationMonster(api_key="sm_live_...")       # or set STATIONMONSTER_API_KEY
    for station in sm.list_stations()["data"]:
        print(station["name"], sm.now_playing(station["id"])["title"])

Docs: https://stationmonster.com/developers/sdk
Keep the methods in step with the API's operations (supabase/functions/_shared/station-api.ts) and the JavaScript SDK.
"""

from __future__ import annotations

import hashlib
import hmac
import json
import os
import time
import uuid
from typing import Any, Callable, Dict, Iterator, List, Optional, Union
from urllib import error as urlerror
from urllib import parse, request

__all__ = ["StationMonster", "StationMonsterError", "verify_webhook", "VERSION", "DEFAULT_BASE_URL"]

VERSION = "1.0.0"
DEFAULT_BASE_URL = "https://api.stationmonster.com/functions/v1/api/v1"
_RETRY = {429, 500, 502, 503, 504}

Row = Dict[str, Any]
Filters = Dict[str, Union[str, int, float, bool, None, List[str]]]


class StationMonsterError(Exception):
    """An error answer from the API."""

    def __init__(self, status: int, body: Optional[Row], retry_after: Optional[float] = None):
        self.status = status
        self.body = body or {}
        self.required_scope = self.body.get("required_scope")
        self.retry_after = retry_after
        super().__init__(self.body.get("error") or f"Request failed with status {status}")


def _q(params: Optional[Row]) -> str:
    pairs: List[tuple] = []
    for k, v in (params or {}).items():
        if v is None or v == "":
            continue
        if k == "filters" and isinstance(v, dict):
            for col, f in v.items():
                for one in f if isinstance(f, list) else [f]:
                    pairs.append((col, "is.null" if one is None else str(one).lower() if isinstance(one, bool) else str(one)))
        else:
            pairs.append((k, str(v).lower() if isinstance(v, bool) else str(v)))
    return ("?" + parse.urlencode(pairs)) if pairs else ""


def _e(s: str) -> str:
    return parse.quote(str(s), safe="")


class StationMonster:
    def __init__(
        self,
        api_key: Optional[str] = None,
        access_token: Optional[str] = None,
        base_url: str = DEFAULT_BASE_URL,
        max_retries: int = 3,
        timeout: float = 30.0,
    ):
        key = api_key or access_token or os.environ.get("STATIONMONSTER_API_KEY")
        if not key:
            raise ValueError("Pass api_key (or access_token), or set STATIONMONSTER_API_KEY.")
        self.key = key
        self.base_url = base_url.rstrip("/")
        self.max_retries = max_retries
        self.timeout = timeout

    # ---------- plumbing ----------
    def raw(self, method: str, path: str, query: Optional[Row] = None, body: Any = None,
            headers: Optional[Dict[str, str]] = None, idempotency_key: Optional[str] = None):
        """Any API call. Returns (data, headers, status). Writes get an Idempotency-Key, so retries never run twice."""
        url = f"{self.base_url}{path}{_q(query)}"
        h = {"X-API-Key": self.key, "Accept": "application/json", "User-Agent": f"stationmonster-python/{VERSION}", **(headers or {})}
        data = None
        if body is not None:
            h["Content-Type"] = "application/json"
            data = json.dumps(body).encode()
        if method != "GET" and not (query or {}).get("dry_run"):
            h["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
        attempt = 0
        while True:
            req = request.Request(url, data=data, method=method, headers=h)
            try:
                with request.urlopen(req, timeout=self.timeout) as res:
                    text = res.read().decode()
                    return (json.loads(text) if text else None), dict(res.headers), res.status
            except urlerror.HTTPError as e:
                text = e.read().decode()
                try:
                    payload = json.loads(text) if text else None
                except ValueError:
                    payload = {"error": text[:300]}
                ra = e.headers.get("Retry-After")
                err = StationMonsterError(e.code, payload, float(ra) if ra else None)
                if e.code not in _RETRY or attempt >= self.max_retries:
                    raise err from None
                time.sleep(err.retry_after or 0.5 * 2 ** attempt)
            except urlerror.URLError:
                if attempt >= self.max_retries:
                    raise
                time.sleep(0.5 * 2 ** attempt)
            attempt += 1

    def request(self, method: str, path: str, **kw) -> Any:
        return self.raw(method, path, **kw)[0]

    def paginate(self, page: Callable[[Optional[str]], Row]) -> Iterator[Row]:
        """Every item of a paged list: for play in sm.paginate(lambda c: sm.plays(sid, cursor=c)): ..."""
        cursor = None
        while True:
            r = page(cursor)
            yield from r.get("data") or []
            if not r.get("has_more"):
                return
            cursor = r.get("next_cursor")

    def watch(self, fn: Callable[[], Any], on_change: Callable[[Any], None], interval: float = 5.0) -> None:
        """Calls fn every `interval` seconds and on_change when its answer changes (blocks; stop with Ctrl+C)."""
        last = None
        while True:
            value = fn()
            text = json.dumps(value, sort_keys=True)
            if text != last:
                last = text
                on_change(value)
            time.sleep(interval)

    # ---------- key, stations, on air ----------
    def me(self) -> Row: return self.request("GET", "/me")
    def list_stations(self) -> Row: return self.request("GET", "/stations")
    def get_station(self, station_id: str) -> Row: return self.request("GET", f"/stations/{_e(station_id)}")
    def now_playing(self, station_id: str) -> Row: return self.request("GET", f"/stations/{_e(station_id)}/now-playing")

    def plays(self, station_id: str, from_: Optional[str] = None, to: Optional[str] = None, type: Optional[str] = None,
              limit: Optional[int] = None, cursor: Optional[str] = None) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/plays", query={"from": from_, "to": to, "type": type, "limit": limit, "cursor": cursor})

    def log(self, station_id: str, date: Optional[str] = None) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/log", query={"date": date})

    def search_library(self, station_id: str, q: Optional[str] = None, type: Optional[str] = None,
                       limit: Optional[int] = None, cursor: Optional[str] = None) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/library", query={"q": q, "type": type, "limit": limit, "cursor": cursor})

    def shows(self, station_id: str) -> Row: return self.request("GET", f"/stations/{_e(station_id)}/shows")

    def requests(self, station_id: str, status: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/requests", query={"status": status, "limit": limit, "cursor": cursor})

    def listeners(self, station_id: str, from_: Optional[str] = None, to: Optional[str] = None) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/listeners", query={"from": from_, "to": to})

    # ---------- running the studio (changes need control:playout) ----------
    def playout(self, station_id: str) -> Row: return self.request("GET", f"/stations/{_e(station_id)}/playout")
    def studios(self, station_id: str) -> Row: return self.request("GET", f"/stations/{_e(station_id)}/studios")

    def send_playout_command(self, station_id: str, command: str, dry_run: bool = False, **body) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/playout/commands", body={"command": command, **body}, query={"dry_run": dry_run or None})

    def skip(self, station_id: str, **kw) -> Row:
        """Starts the next item; what's on air fades out as at a segue."""
        return self.send_playout_command(station_id, "play_next", **kw)

    play_next = skip
    def play_player(self, station_id: str, player: int, **kw) -> Row: return self.send_playout_command(station_id, "play_player", player=player, **kw)
    def stop_player(self, station_id: str, player: int, fade: bool = True, **kw) -> Row: return self.send_playout_command(station_id, "stop_player", player=player, fade=fade, **kw)
    def pause_player(self, station_id: str, player: int, **kw) -> Row: return self.send_playout_command(station_id, "pause_player", player=player, **kw)
    def recue_player(self, station_id: str, player: int, **kw) -> Row: return self.send_playout_command(station_id, "recue_player", player=player, **kw)
    def stop_all(self, station_id: str, **kw) -> Row: return self.send_playout_command(station_id, "stop_all", **kw)
    def set_mode(self, station_id: str, mode: str, **kw) -> Row: return self.send_playout_command(station_id, "set_mode", mode=mode, **kw)
    def jump_to(self, station_id: str, log_item_id: str, **kw) -> Row: return self.send_playout_command(station_id, "jump_to", log_item_id=log_item_id, **kw)
    def fire_cart(self, station_id: str, cart_id: str, **kw) -> Row: return self.send_playout_command(station_id, "fire_cart", cart_id=cart_id, **kw)

    def set_level(self, station_id: str, fader: str, level: float, **kw) -> Row:
        """Moves a fader (player1, player2, player3 or carts): 0 = off, 0.75 = the U mark, 1 = top. Cloud engine only."""
        return self.send_playout_command(station_id, "set_level", fader=fader, level=level, **kw)

    def set_on_air_control(self, station_id: str, action: str, studio_id: Optional[str] = None, take_over: bool = False, dry_run: bool = False) -> Row:
        """action: "take" (a studio PC you're signed in at), "hand" (to another studio) or "release"."""
        return self.request("POST", f"/stations/{_e(station_id)}/studio/control", body={"action": action, "studio_id": studio_id, "take_over": take_over or None}, query={"dry_run": dry_run or None})

    def take_control(self, station_id: str, studio_id: str, **kw) -> Row: return self.set_on_air_control(station_id, "take", studio_id, **kw)
    def hand_control(self, station_id: str, studio_id: str, **kw) -> Row: return self.set_on_air_control(station_id, "hand", studio_id, **kw)
    def release_control(self, station_id: str, **kw) -> Row: return self.set_on_air_control(station_id, "release", **kw)

    def set_cohost(self, station_id: str, studio_id: str, on: bool, dry_run: bool = False) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/studio/cohosts", body={"studio_id": studio_id, "on": on}, query={"dry_run": dry_run or None})

    def set_mute_audio(self, station_id: str, on: bool, studio_id: Optional[str] = None, dry_run: bool = False) -> Row:
        """Mute audio in everyone's talkback headphones (never air)."""
        return self.request("POST", f"/stations/{_e(station_id)}/studio/mute", body={"on": on, "studio_id": studio_id}, query={"dry_run": dry_run or None})

    def set_now_playing_text(self, station_id: str, text: Optional[str], dry_run: bool = False) -> Row:
        """Your own now-playing text on streams and radio displays; None or "" = back to automatic."""
        return self.request("POST", f"/stations/{_e(station_id)}/now-playing/text", body={"text": text or ""}, query={"dry_run": dry_run or None})

    def playout_command(self, station_id: str, command_id: str) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/playout/commands/{_e(command_id)}")

    def wait_for_command(self, station_id: str, command_id: str, timeout: float = 35.0, interval: float = 1.0) -> Row:
        """Waits until the engine has run a command (status done) or dropped it (expired)."""
        until = time.time() + timeout
        while True:
            c = self.playout_command(station_id, command_id)
            if c.get("status") != "waiting" or time.time() > until:
                return c
            time.sleep(interval)

    # ---------- the log ----------
    def add_log_entry(self, station_id: str, date: str, media_id: str, before_id: Optional[str] = None,
                      hour: Optional[int] = None, dry_run: bool = False) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/log/entries", body={"date": date, "media_id": media_id, "before_id": before_id, "hour": hour}, query={"dry_run": dry_run or None})

    def move_log_entry(self, station_id: str, item_id: str, before_id: Optional[str] = None, hour: Optional[int] = None,
                       date: Optional[str] = None, dry_run: bool = False) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/log/entries/{_e(item_id)}/move", body={"before_id": before_id, "hour": hour, "date": date}, query={"dry_run": dry_run or None})

    def swap_log_entries(self, station_id: str, item_id: str, with_id: str, dry_run: bool = False) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/log/entries/{_e(item_id)}/swap", body={"with_id": with_id}, query={"dry_run": dry_run or None})

    def remove_log_entry(self, station_id: str, item_id: str, dry_run: bool = False) -> Row:
        return self.request("DELETE", f"/stations/{_e(station_id)}/log/entries/{_e(item_id)}", query={"dry_run": dry_run or None})

    # ---------- records ----------
    def list_resources(self, q: Optional[str] = None) -> Row: return self.request("GET", "/resources", query={"q": q})
    def describe_resource(self, resource: str) -> Row: return self.request("GET", f"/resources/{_e(resource)}")

    def list_records(self, resource: str, filters: Optional[Filters] = None, select: Optional[str] = None, order: Optional[str] = None,
                     count: Optional[bool] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> Row:
        return self.request("GET", f"/resources/{_e(resource)}/records", query={"filters": filters, "select": select, "order": order, "count": count, "limit": limit, "cursor": cursor})

    def get_record(self, resource: str, id: str, select: Optional[str] = None):
        """Returns (record, etag): pass etag as if_match to change or delete it safely."""
        data, headers, _ = self.raw("GET", f"/resources/{_e(resource)}/records/{_e(id)}", query={"select": select})
        return data, {k.lower(): v for k, v in headers.items()}.get("etag")

    def create_records(self, resource: str, records: Union[Row, List[Row]], upsert: bool = False, select: Optional[str] = None, dry_run: bool = False) -> Row:
        return self.request("POST", f"/resources/{_e(resource)}/records", body=records, query={"upsert": upsert or None, "select": select, "dry_run": dry_run or None})

    def update_record(self, resource: str, id: str, values: Row, if_match: Optional[str] = None, select: Optional[str] = None, dry_run: bool = False):
        data, headers, _ = self.raw("PATCH", f"/resources/{_e(resource)}/records/{_e(id)}", body=values, query={"select": select, "dry_run": dry_run or None},
                                    headers={"If-Match": if_match} if if_match else None)
        return data, {k.lower(): v for k, v in headers.items()}.get("etag")

    def update_records(self, resource: str, filters: Filters, values: Row, dry_run: bool = False) -> Row:
        return self.request("PATCH", f"/resources/{_e(resource)}/records", body=values, query={"filters": filters, "dry_run": dry_run or None})

    def delete_record(self, resource: str, id: str, if_match: Optional[str] = None, dry_run: bool = False) -> Row:
        return self.request("DELETE", f"/resources/{_e(resource)}/records/{_e(id)}", query={"dry_run": dry_run or None}, headers={"If-Match": if_match} if if_match else None)

    def delete_records(self, resource: str, filters: Filters, dry_run: bool = False) -> Row:
        return self.request("DELETE", f"/resources/{_e(resource)}/records", query={"filters": filters, "dry_run": dry_run or None})

    # ---------- actions ----------
    def list_actions(self, q: Optional[str] = None) -> Row: return self.request("GET", "/actions", query={"q": q})

    def call_action(self, name: str, args: Optional[Row] = None, dry_run: bool = False) -> Any:
        return self.request("POST", f"/actions/{_e(name)}", body=args or {}, query={"dry_run": dry_run or None})

    # ---------- audio ----------
    def media_audio(self, station_id: str, media_id: str) -> Row:
        return self.request("GET", f"/stations/{_e(station_id)}/library/{_e(media_id)}/audio")

    def create_upload(self, station_id: str, ext: str, size: int) -> Row:
        return self.request("POST", f"/stations/{_e(station_id)}/library/uploads", body={"ext": ext, "size": size})

    def upload_audio(self, station_id: str, data: bytes, ext: str, content_type: str = "application/octet-stream") -> Row:
        """Uploads audio bytes; returns {storage_path, storage_provider} for a media_items record."""
        up = self.create_upload(station_id, ext, len(data))
        req = request.Request(up["upload_url"], data=data, method=up.get("method") or "PUT", headers={"Content-Type": content_type, **(up.get("headers") or {})})
        try:
            with request.urlopen(req, timeout=max(self.timeout, 600)):
                pass
        except urlerror.HTTPError as e:
            raise StationMonsterError(e.code, {"error": f"The upload was refused ({e.code})."}) from None
        return {"storage_path": up["storage_path"], "storage_provider": up["storage_provider"]}

    def add_to_library(self, station_id: str, path: str, title: str, content_type: str = "application/octet-stream", **fields) -> Row:
        """Uploads a file from disk and creates the library item (fields: category or category_id, artist, duration_ms, …)."""
        with open(path, "rb") as f:
            data = f.read()
        ext = os.path.splitext(path)[1].lstrip(".").lower() or "mp3"
        stored = self.upload_audio(station_id, data, ext, content_type)
        return self.create_records("media_items", {"station_id": station_id, "title": title, **fields, **stored})["data"][0]


def verify_webhook(raw_body: Union[str, bytes], signature_header: Optional[str], secret: str, tolerance: int = 300) -> bool:
    """Checks a webhook delivery's X-StationMonster-Signature header. Pass the raw body exactly as received."""
    if not signature_header or not secret:
        return False
    parts = dict(p.strip().split("=", 1) for p in signature_header.split(",") if "=" in p)
    try:
        t = int(parts.get("t", "0"))
    except ValueError:
        return False
    if not t or "v1" not in parts or abs(time.time() - t) > tolerance:
        return False
    body = raw_body.decode() if isinstance(raw_body, bytes) else raw_body
    mac = hmac.new(secret.encode(), f"{t}.{body}".encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(mac, parts["v1"])
