"""terrycalls: Terry's Bitcoin Up/Down calls from the Terry Calls API (v2). One file, Python 3.8+, no dependencies.

    from terrycalls import Client
    terry = Client("tc_live_...")            # or set TERRY_API_KEY
    for m in terry.calls()["markets"]:
        print(m["horizon"], m["status"], m["call"])

Every GET remembers its ETag and sends it back, so an unchanged answer costs a quick 304 and you get the copy you already have. Errors raise
TerryError with the API's error code, message and (for 429) how long to wait. Docs: https://terrycalls.com/developers/v2"""
from __future__ import annotations

import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request

__version__ = "0.4.0"
__all__ = ["Client", "TerryError", "verify_webhook"]

BASE = "https://terrycalls.com"


class TerryError(Exception):
    def __init__(self, status: int, error: str, message: str = "", retry_after: float | None = None):
        super().__init__(f"{status} {error}: {message}" if message else f"{status} {error}")
        self.status, self.error, self.message, self.retry_after = status, error, message, retry_after


class Client:
    def __init__(self, key: str | None = None, base: str = BASE, timeout: float = 10.0, user_agent: str | None = None):
        self.key = key or os.environ.get("TERRY_API_KEY") or ""
        if not self.key:
            raise ValueError("An API key is needed: Client('tc_live_...') or TERRY_API_KEY. Get one free at https://terrycalls.com/developers/keys")
        self.base, self.timeout = base.rstrip("/"), timeout
        self.user_agent = user_agent or f"terrycalls-python/{__version__}"
        self._etags: dict = {}                    # url -> (etag, answer)

    # -- plumbing
    def _url(self, path: str, params: dict) -> str:
        query = {k: ("1" if v is True else ",".join(v) if isinstance(v, (list, tuple)) else v) for k, v in params.items() if v not in (None, False)}
        return self.base + path + ("?" + urllib.parse.urlencode(query) if query else "")

    def _request(self, url: str, headers: dict | None = None):
        head = {"X-API-Key": self.key, "User-Agent": self.user_agent, "Accept": "application/json", **(headers or {})}
        return urllib.request.urlopen(urllib.request.Request(url, headers=head), timeout=self.timeout)

    def _raise(self, exc: urllib.error.HTTPError):
        try:
            body = json.loads(exc.read() or b"{}")
        except ValueError:
            body = {}
        retry = exc.headers.get("Retry-After")
        raise TerryError(exc.code, body.get("error", "http_error"), body.get("message", ""), float(retry) if retry else None) from None

    def get(self, path: str, **params):
        """Any GET under /api/v2, e.g. get("/api/v2/stats", horizon="5m", by="hour")."""
        url = self._url(path, params)
        cached = self._etags.get(url)
        try:
            with self._request(url, {"If-None-Match": cached[0]} if cached else None) as res:
                raw = res.read()
                kind = res.headers.get("Content-Type", "")
                data = json.loads(raw) if "json" in kind else raw.decode("utf-8")
                tag = res.headers.get("ETag")
        except urllib.error.HTTPError as exc:
            if exc.code == 304 and cached:
                return cached[1]
            self._raise(exc)
        if tag:
            if len(self._etags) > 500:
                self._etags.clear()
            self._etags[url] = (tag, data)
        return data

    # -- the endpoints (https://terrycalls.com/developers/v2#endpoints)
    def calls(self, horizon=None, **kw):
        return self.get("/api/v2/calls", horizon=horizon, **kw)

    def overview(self, horizon=None, days=None, **kw):
        return self.get("/api/v2/overview", horizon=horizon, days=days, **kw)

    def windows(self, horizon=None, days=None, limit=None, only=None, side=None, min_chance=None, max_chance=None, hours=None, rule=None, before=None, **kw):
        return self.get("/api/v2/windows", horizon=horizon, days=days, limit=limit, only=only, side=side, min_chance=min_chance,
                        max_chance=max_chance, hours=hours, rule=rule, before=before, **kw)

    def iter_windows(self, **filters):
        """Every window that matches, newest first, page by page."""
        before = filters.pop("before", None)
        while True:
            page = self.windows(before=before, **filters)
            yield from page["windows"]
            before = page.get("next_before")
            if not before:
                return

    def windows_csv(self, **filters) -> str:
        return self.get("/api/v2/windows", format="csv", **filters)

    def window(self, market=None, at=None, horizon=None):
        return self.get("/api/v2/window", market=market, at=at, horizon=horizon)

    def stats(self, by="chance", horizon=None, days=None, kind=None, rule=None, **kw):
        return self.get("/api/v2/stats", by=by, horizon=horizon, days=days, kind=kind, rule=rule, **kw)

    def calibration(self, horizon=None, days=None, kind=None, rule=None, **kw):
        return self.get("/api/v2/calibration", horizon=horizon, days=days, kind=kind, rule=rule, **kw)

    def trend(self, horizon=None, days=None, block=None, kind=None, rule=None, **kw):
        return self.get("/api/v2/trend", horizon=horizon, days=days, block=block, kind=kind, rule=rule, **kw)

    def flips(self, horizon=None, days=None, **kw):
        return self.get("/api/v2/flips", horizon=horizon, days=days, **kw)

    def follow(self, stake=None, horizon=None, days=None, kind=None, rule=None, **kw):
        return self.get("/api/v2/follow", stake=stake, horizon=horizon, days=days, kind=kind, rule=rule, **kw)

    def streaks(self, horizon=None, days=None, rule=None, **kw):
        return self.get("/api/v2/streaks", horizon=horizon, days=days, rule=rule, **kw)

    def daily(self, horizon=None, days=None, rule=None, **kw):
        return self.get("/api/v2/daily", horizon=horizon, days=days, rule=rule, **kw)

    def locks(self, horizon=None, days=None, rule=None, **kw):
        return self.get("/api/v2/locks", horizon=horizon, days=days, rule=rule, **kw)

    def rules(self, horizon=None):
        return self.get("/api/v2/rules", horizon=horizon)

    def record(self, days=None):
        return self.get("/api/v2/record", days=days)

    def best_times(self, horizon=None):
        return self.get("/api/v2/best-times", horizon=horizon)

    def kalshi(self, horizon=None, history=False):
        """Kalshi's price for the same 15m/1h windows beside Polymarket's, and the gap (0.3.0). history=True adds the window's Kalshi
        Yes mid every second."""
        return self.get("/api/v2/kalshi", horizon=horizon, history=1 if history else None)

    def backtest(self, horizon=None, days=None, rule=None, kind=None, stake=None, fee=None, csv=False, **filters):
        """What a fixed stake on one rule's calls (or locks) would have made, with the fee you pay (0.4.0). fee: "api" (the API taker fee with
        its 70% rebate), "standard" or "maker"; filters: min_price, max_price, min_chance, max_chance, hours ("8-20"), side, min_seconds_in,
        max_seconds_in. csv=True (Unlimited plan) returns one row a trade as text."""
        return self.get("/api/v2/backtest", horizon=horizon, days=days, rule=rule, kind=kind, stake=stake, fee=fee,
                        format="csv" if csv else None, **filters)

    def status(self):
        """The API's live checks, uptime and incidents (0.4.0). No key needed."""
        return self.get("/api/v2/status")

    def usage(self):
        return self.get("/api/v2/usage")

    def changelog(self, limit=None):
        return self.get("/api/v2/changelog", limit=limit)

    # -- Terry's events on any plan (Nov 20 2026): wait for the next one instead of polling
    def events(self, since=None, wait=None, types=None, horizon=None) -> dict:
        """One GET /api/v2/events: {"seq", "events", "missed", "next"}. With `since` (the seq of the last event you have) it returns what
        happened after it at once, or waits up to `wait` seconds (0-30) for the next. One request however long it waits."""
        url = self._url("/api/v2/events", {"since": since, "wait": wait, "types": types, "horizon": horizon})
        head = {"X-API-Key": self.key, "User-Agent": self.user_agent, "Accept": "application/json"}
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=head), timeout=(wait or 0) + 15) as res:
                return json.loads(res.read())
        except urllib.error.HTTPError as exc:
            self._raise(exc)

    def watch(self, types=None, horizon=None, since=None, wait: int = 30):
        """Every event from now on (or after `since`), as it happens: window / call / lock / settled ({"seq", "type", "at", "horizon",
        "market", "data"}). Keeps its place across network blips and waits out 429s; an event with "type": "missed" means some were lost
        while away (refill from windows()). Free on any plan, about two requests a minute.
            for ev in terry.watch(types=["call", "lock"]):
                print(ev["horizon"], ev["type"], ev["data"]["side"])"""
        cursor = since
        pause = 1.0
        while True:
            try:
                got = self.events(since=cursor, wait=wait if cursor is not None else 0, types=types, horizon=horizon)
            except TerryError as exc:
                if exc.status in (429, 503) or exc.status >= 500:
                    time.sleep(exc.retry_after or pause)
                    pause = min(pause * 2, 60.0)
                    continue
                raise
            except OSError:
                time.sleep(pause)
                pause = min(pause * 2, 60.0)
                continue
            pause = 1.0
            if got.get("missed") and cursor is not None:
                yield {"type": "missed", "seq": got.get("seq"), "data": {"since": cursor}}
            for ev in got.get("events") or []:
                yield ev
            cursor = got.get("seq", cursor)

    # -- the live stream (Unlimited plan)
    def stream(self, types=None, horizon=None, last_event_id=None, reconnect: bool = True):
        """Events as they happen: {"type": "snapshot", "data": <the live calls>} first, then window / call / lock / settled events
        ({"seq", "type", "at", "horizon", "market", "data"}). A dropped connection is picked up again with Last-Event-ID, so nothing in
        between is missed (from about the last day). Stops on an "end" event or, with reconnect=False, when the connection closes."""
        last = last_event_id
        wait = 1.0
        while True:
            headers = {"Accept": "text/event-stream"}
            if last:
                headers["Last-Event-ID"] = str(last)
            try:
                res = urllib.request.urlopen(urllib.request.Request(self._url("/api/v2/stream", {"types": types, "horizon": horizon}),
                                             headers={"X-API-Key": self.key, "User-Agent": self.user_agent, **headers}), timeout=60)
            except urllib.error.HTTPError as exc:
                self._raise(exc)
            except OSError:
                if not reconnect:
                    raise
                time.sleep(wait)
                wait = min(wait * 2, 30.0)
                continue
            wait = 1.0
            event, data, eid = None, [], None
            try:
                with res:
                    for raw in res:
                        line = raw.decode("utf-8").rstrip("\r\n")
                        if not line:
                            if event and data:
                                body = json.loads("\n".join(data))
                                if eid:
                                    last = eid
                                if event == "snapshot":
                                    yield {"type": "snapshot", "seq": int(eid) if eid else None, "data": body}
                                elif event == "end":
                                    yield {"type": "end", "data": body}
                                    return
                                else:
                                    yield body
                            event, data, eid = None, [], None
                        elif line.startswith(":"):
                            continue
                        elif line.startswith("event:"):
                            event = line[6:].strip()
                        elif line.startswith("data:"):
                            data.append(line[5:].lstrip())
                        elif line.startswith("id:"):
                            eid = line[3:].strip()
            except OSError:
                pass
            if not reconnect:
                return
            time.sleep(wait)


def verify_webhook(secret: str, body: bytes, signature: str, tolerance: float = 300, now: float | None = None) -> dict:
    """The event in a webhook delivery, once its Terry-Signature header checks out; TerryError otherwise. Pass the raw body bytes."""
    try:
        parts = dict(p.split("=", 1) for p in (signature or "").split(","))
        t = int(parts["t"])
    except (ValueError, KeyError):
        raise TerryError(401, "bad_signature", "No Terry-Signature, or not t=..,v1=..") from None
    good = hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(good, parts.get("v1", "")):
        raise TerryError(401, "bad_signature", "The signature does not match this secret.")
    if abs((time.time() if now is None else now) - t) > tolerance:
        raise TerryError(401, "too_old", "The delivery is older than the tolerance (a replay?).")
    return json.loads(body)
