#!/usr/bin/env python3
"""
Kalshi - Coinbase BTC 15-minute LAG MONITOR  (Phase 1: read-only signal display)

What it does
------------
Polls two PUBLIC, unauthenticated feeds every ~1.5 seconds:
  * Coinbase BTC-USD spot price
  * Kalshi public market data for the current 15-minute BTC market
    (series KXBTC15M): target (floor strike), Yes bid/ask, order book depth

Shows a small always-on-top window: spot, Kalshi target, spot-minus-target
gap, Yes bid/ask, seconds left in the window, and a simple edge readout
(a rough normal-model probability from the spot gap and recent volatility,
minus the Kalshi mid price, in cents).

Every sample is appended to a CSV log next to this script and the latest
sample is written to latest.json in a stable schema, so the same feed can
later power a phone-friendly web view.

HARD LIMITS: read-only. No logins, no API keys, no order placement, ever.
This file contains no trading code on purpose.

Run:
  python kalshi_lag_monitor.py              -> floating window
  python kalshi_lag_monitor.py --headless 5 -> print 5 samples, no window
"""

import argparse
import csv
import json
import math
import os
import sys
import threading
import time
import urllib.request
from datetime import datetime, timezone

# --------------------------------------------------------------------------
# Config
# --------------------------------------------------------------------------
SERIES_TICKER = "KXBTC15M"
COINBASE_SPOT_URL = "https://api.coinbase.com/v2/prices/BTC-USD/spot"
# The /v2 spot endpoint is cached in steps; the public Exchange ticker is
# tick-fresh, which matters for a lag monitor. Prefer the ticker, fall back
# to the spot endpoint. Both are public and unauthenticated.
COINBASE_TICKER_URL = "https://api.exchange.coinbase.com/products/BTC-USD/ticker"
COINBASE_PREFER_TICKER = True
KALSHI_MARKETS_URL = (
    "https://api.elections.kalshi.com/trade-api/v2/markets"
    "?series_ticker=%s&status=open&limit=10" % SERIES_TICKER
)
KALSHI_ORDERBOOK_URL = (
    "https://api.elections.kalshi.com/trade-api/v2/markets/%s/orderbook"
)
DEFAULT_POLL_SECONDS = 1.5
HTTP_TIMEOUT = 5

HERE = os.path.dirname(os.path.abspath(__file__))
LOG_CSV = os.path.join(HERE, "kalshi_lag_log.csv")
LATEST_JSON = os.path.join(HERE, "latest.json")

LOG_FIELDS = [
    "ts_iso", "epoch", "ticker", "coinbase_spot", "spot_source", "kalshi_target",
    "gap_usd", "gap_pct", "yes_bid_c", "yes_ask_c", "yes_mid_c",
    "model_prob", "edge_c", "seconds_left", "spot_move_10s",
    "book_yes_levels", "book_no_levels", "error",
]


# --------------------------------------------------------------------------
# Data layer (no GUI imports here - this is the part a future web view reuses)
# --------------------------------------------------------------------------
def fetch_json(url):
    req = urllib.request.Request(url, headers={"User-Agent": "kalshi-lag-monitor/1.0"})
    with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
        return json.loads(resp.read().decode("utf-8"))


def parse_iso_z(text):
    return datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)


def fetch_coinbase_spot():
    """Returns (price, source). Prefers the tick-fresh Exchange ticker;
    falls back to the (cached) spot endpoint from the original spec."""
    if COINBASE_PREFER_TICKER:
        try:
            data = fetch_json(COINBASE_TICKER_URL)
            return float(data["price"]), "coinbase-exchange-ticker"
        except Exception:
            pass
    data = fetch_json(COINBASE_SPOT_URL)
    return float(data["data"]["amount"]), "coinbase-spot"


def fetch_current_market(now):
    """Return the Kalshi market dict for the window currently trading."""
    data = fetch_json(KALSHI_MARKETS_URL)
    markets = data.get("markets") or []
    candidates = []
    for m in markets:
        try:
            close_dt = parse_iso_z(m["close_time"])
        except Exception:
            continue
        if close_dt > now:
            candidates.append((close_dt, m))
    if not candidates:
        return None
    candidates.sort(key=lambda pair: pair[0])
    return candidates[0][1]


def fetch_orderbook_top(ticker):
    """Best Yes bid and book depth from the order book. Tolerates empty books
    and both the current (orderbook_fp, dollar strings) and legacy
    (orderbook, cent ints) response shapes. Returns (best_yes_bid_dollars,
    yes_levels, no_levels) with None values when unavailable."""
    try:
        data = fetch_json(KALSHI_ORDERBOOK_URL % ticker)
    except Exception:
        return None, None, None
    book = data.get("orderbook_fp") or data.get("orderbook") or {}
    yes = book.get("yes_dollars") or book.get("yes") or []
    no = book.get("no_dollars") or book.get("no") or []
    best_yes_bid = None
    if yes:
        try:
            prices = [float(row[0]) for row in yes]
            # Legacy shape is in cents (ints > 1); normalize to dollars.
            if max(prices) > 1.0:
                prices = [p / 100.0 for p in prices]
            best_yes_bid = max(prices)
        except Exception:
            best_yes_bid = None
    return best_yes_bid, len(yes), len(no)


def norm_cdf(x):
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


class SpotHistory:
    """Rolling spot samples used for a simple realized-volatility estimate."""

    def __init__(self, maxlen=240):
        self.samples = []  # list of (epoch, price)
        self.maxlen = maxlen

    def add(self, epoch, price):
        self.samples.append((epoch, price))
        if len(self.samples) > self.maxlen:
            self.samples = self.samples[-self.maxlen:]

    def move_over(self, seconds):
        if not self.samples:
            return None
        now_t, now_p = self.samples[-1]
        target = now_t - seconds
        past = None
        for t, p in self.samples:
            if t <= target:
                past = p
            else:
                break
        if past is None:
            return None
        return now_p - past

    def per_second_vol(self):
        """Stdev of per-second log returns; None until enough history."""
        if len(self.samples) < 20:
            return None
        rets = []
        for (t0, p0), (t1, p1) in zip(self.samples, self.samples[1:]):
            dt = t1 - t0
            if dt <= 0 or p0 <= 0 or p1 <= 0:
                continue
            rets.append(math.log(p1 / p0) / math.sqrt(dt))
        if len(rets) < 15:
            return None
        mean = sum(rets) / len(rets)
        var = sum((r - mean) ** 2 for r in rets) / (len(rets) - 1)
        return math.sqrt(var)


class LagMonitor:
    """Polls both feeds and produces one sample dict per poll."""

    def __init__(self):
        self.history = SpotHistory()
        self.latest = None
        self._lock = threading.Lock()

    def poll_once(self):
        now = datetime.now(timezone.utc)
        epoch = now.timestamp()
        sample = {
            "ts_iso": now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
            "epoch": round(epoch, 3),
            "ticker": None,
            "coinbase_spot": None,
            "spot_source": None,
            "kalshi_target": None,
            "gap_usd": None,
            "gap_pct": None,
            "yes_bid_c": None,
            "yes_ask_c": None,
            "yes_mid_c": None,
            "model_prob": None,
            "edge_c": None,
            "seconds_left": None,
            "spot_move_10s": None,
            "book_yes_levels": None,
            "book_no_levels": None,
            "error": "",
        }
        errors = []
        spot = None
        try:
            spot, source = fetch_coinbase_spot()
            sample["coinbase_spot"] = round(spot, 2)
            sample["spot_source"] = source
            self.history.add(epoch, spot)
        except Exception as exc:  # network hiccup - keep going, mark sample
            errors.append("coinbase: %s" % exc)

        market = None
        try:
            market = fetch_current_market(now)
        except Exception as exc:
            errors.append("kalshi: %s" % exc)

        if market is not None:
            sample["ticker"] = market.get("ticker")
            strike = market.get("floor_strike")
            if strike is not None:
                sample["kalshi_target"] = float(strike)
            try:
                close_dt = parse_iso_z(market["close_time"])
                sample["seconds_left"] = max(0, int((close_dt - now).total_seconds()))
            except Exception:
                pass

            def dollars(key):
                raw = market.get(key)
                if raw in (None, ""):
                    return None
                try:
                    return float(raw)
                except Exception:
                    return None

            yes_bid = dollars("yes_bid_dollars")
            yes_ask = dollars("yes_ask_dollars")
            book_bid, yes_levels, no_levels = fetch_orderbook_top(market.get("ticker", ""))
            sample["book_yes_levels"] = yes_levels
            sample["book_no_levels"] = no_levels
            if yes_bid is None and book_bid is not None:
                yes_bid = book_bid
            if yes_bid is not None:
                sample["yes_bid_c"] = round(yes_bid * 100, 1)
            if yes_ask is not None:
                sample["yes_ask_c"] = round(yes_ask * 100, 1)
            if yes_bid is not None and yes_ask is not None:
                sample["yes_mid_c"] = round((yes_bid + yes_ask) * 50, 1)

        if spot is not None:
            sample["spot_move_10s"] = (
                round(self.history.move_over(10), 2)
                if self.history.move_over(10) is not None else None
            )
        if spot is not None and sample["kalshi_target"]:
            gap = spot - sample["kalshi_target"]
            sample["gap_usd"] = round(gap, 2)
            sample["gap_pct"] = round(gap / spot * 100, 4)
            # Simple edge model: P(final avg >= target) approximated with a
            # normal model on the current gap and realized volatility scaled
            # to the time left. Deliberately rough - a signal, not a promise.
            vol = self.history.per_second_vol()
            secs = sample["seconds_left"]
            if vol and secs and secs > 0 and spot > 0:
                sigma_t = vol * math.sqrt(secs)
                if sigma_t > 0:
                    z = math.log(spot / sample["kalshi_target"]) / sigma_t
                    sample["model_prob"] = round(norm_cdf(z), 4)
            if sample["model_prob"] is not None and sample["yes_mid_c"] is not None:
                sample["edge_c"] = round(
                    (sample["model_prob"] * 100) - sample["yes_mid_c"], 1
                )

        sample["error"] = "; ".join(errors)
        with self._lock:
            self.latest = sample
        return sample

    def get_latest(self):
        with self._lock:
            return dict(self.latest) if self.latest else None


# --------------------------------------------------------------------------
# Logging (CSV history for later lag statistics + latest.json for reuse)
# --------------------------------------------------------------------------
def append_log(sample):
    new_file = not os.path.exists(LOG_CSV)
    try:
        with open(LOG_CSV, "a", newline="") as fh:
            writer = csv.DictWriter(fh, fieldnames=LOG_FIELDS)
            if new_file:
                writer.writeheader()
            writer.writerow({k: sample.get(k) for k in LOG_FIELDS})
    except Exception:
        pass  # logging must never kill the display


def write_latest(sample):
    try:
        tmp = LATEST_JSON + ".tmp"
        with open(tmp, "w") as fh:
            json.dump(sample, fh, indent=2)
        os.replace(tmp, LATEST_JSON)
    except Exception:
        pass


def poll_loop(monitor, interval, stop_event=None):
    while stop_event is None or not stop_event.is_set():
        sample = monitor.poll_once()
        append_log(sample)
        write_latest(sample)
        if stop_event is not None:
            stop_event.wait(interval)
        else:
            time.sleep(interval)


# --------------------------------------------------------------------------
# GUI (imported lazily so headless mode works anywhere)
# --------------------------------------------------------------------------
def run_gui(monitor, interval):
    import tkinter as tk

    stop_event = threading.Event()
    thread = threading.Thread(
        target=poll_loop, args=(monitor, interval, stop_event), daemon=True
    )
    thread.start()

    root = tk.Tk()
    root.title("BTC 15m Lag Monitor")
    root.attributes("-topmost", True)
    root.resizable(False, False)
    root.configure(bg="#101418")

    fg = "#e8edf2"
    dim = "#8fa3b8"
    mono = ("Consolas", 12)
    big = ("Consolas", 17, "bold")

    def row(label):
        frame = tk.Frame(root, bg="#101418")
        frame.pack(fill="x", padx=10, pady=1)
        tk.Label(frame, text=label, fg=dim, bg="#101418",
                 font=("Consolas", 10), width=13, anchor="w").pack(side="left")
        value = tk.Label(frame, text="--", fg=fg, bg="#101418",
                         font=mono, anchor="w")
        value.pack(side="left")
        return value

    lbl_spot = row("Coinbase BTC")
    lbl_target = row("Kalshi target")
    lbl_gap = row("Gap spot-tgt")
    lbl_book = row("Kalshi Yes")
    lbl_clock = row("Window ends")
    lbl_edge = row("Edge (model)")
    for lbl in (lbl_spot, lbl_target, lbl_gap, lbl_book):
        lbl.configure(font=big)
    lbl_edge.configure(font=big)
    status = tk.Label(root, text="starting...", fg=dim, bg="#101418",
                      font=("Consolas", 9), anchor="w")
    status.pack(fill="x", padx=10, pady=(4, 6))

    def money(v):
        return "$--" if v is None else "${:,.2f}".format(v)

    def refresh():
        s = monitor.get_latest()
        if s:
            lbl_spot.configure(text=money(s["coinbase_spot"]))
            lbl_target.configure(text=money(s["kalshi_target"]))
            if s["gap_usd"] is None:
                lbl_gap.configure(text="--", fg=fg)
            else:
                lbl_gap.configure(
                    text="{:+,.2f}".format(s["gap_usd"]),
                    fg="#3ddc84" if s["gap_usd"] >= 0 else "#ff6b6b",
                )
            if s["yes_bid_c"] is None and s["yes_ask_c"] is None:
                lbl_book.configure(text="no quotes")
            else:
                lbl_book.configure(
                    text="bid {}  ask {}".format(
                        "--" if s["yes_bid_c"] is None else "{:.0f}c".format(s["yes_bid_c"]),
                        "--" if s["yes_ask_c"] is None else "{:.0f}c".format(s["yes_ask_c"]),
                    )
                )
            secs = s["seconds_left"]
            if secs is None:
                lbl_clock.configure(text="--")
            else:
                lbl_clock.configure(text="{}:{:02d} left".format(secs // 60, secs % 60))
            if s["edge_c"] is None:
                lbl_edge.configure(text="warming up", fg=dim)
            else:
                lbl_edge.configure(
                    text="{:+.1f}c vs mid".format(s["edge_c"]),
                    fg="#3ddc84" if s["edge_c"] > 0 else "#ff6b6b",
                )
            age = time.time() - (s["epoch"] or time.time())
            status.configure(
                text="{} | updated {:.0f}s ago{}".format(
                    s["ticker"] or "no market",
                    age,
                    " | " + s["error"] if s["error"] else "",
                )
            )
        root.after(400, refresh)

    def on_close():
        stop_event.set()
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_close)
    refresh()
    root.mainloop()


# --------------------------------------------------------------------------
def main():
    parser = argparse.ArgumentParser(description="Kalshi-Coinbase BTC lag monitor")
    parser.add_argument("--headless", type=int, default=0,
                        help="print N samples as JSON lines and exit (no window)")
    parser.add_argument("--interval", type=float, default=DEFAULT_POLL_SECONDS,
                        help="poll interval in seconds (default 1.5)")
    args = parser.parse_args()

    monitor = LagMonitor()
    if args.headless:
        for _ in range(args.headless):
            sample = monitor.poll_once()
            append_log(sample)
            write_latest(sample)
            print(json.dumps(sample))
            sys.stdout.flush()
            time.sleep(args.interval)
        return
    run_gui(monitor, args.interval)


if __name__ == "__main__":
    main()
