"""
dashboard.py — Optional terminal dashboard for any starter.

Tail the JSONL log file produced by JsonlLogger and render a live status
table with rich. Run in a second terminal alongside the bot:

    python dashboard.py logs/copy_v1

It looks for the most recent file matching `<prefix>-YYYY-MM-DD.jsonl` and
follows it. Adapt the columns to your strategy.
"""

from __future__ import annotations

import json
import os
import sys
import time
from collections import deque
from datetime import datetime
from pathlib import Path

try:
    from rich.console import Console
    from rich.live import Live
    from rich.table import Table
except ImportError:
    print("pip install rich")
    sys.exit(1)


def latest_log(prefix: str) -> Path | None:
    base = Path(prefix)
    parent = base.parent if base.parent.parts else Path(".")
    name = base.name
    candidates = sorted(parent.glob(f"{name}-*.jsonl"))
    return candidates[-1] if candidates else None


def follow(path: Path):
    """Generator yielding new lines as they're written to the file."""
    with path.open("r") as f:
        f.seek(0, 2)  # seek to end
        while True:
            line = f.readline()
            if not line:
                time.sleep(0.5)
                continue
            yield line


def render(events: deque) -> Table:
    table = Table(title=f"Polymarket bot — {datetime.now().strftime('%H:%M:%S')}")
    table.add_column("Time", style="dim", width=8)
    table.add_column("Event", style="cyan", width=22)
    table.add_column("Market", style="green", width=40, no_wrap=True)
    table.add_column("Size", justify="right", width=10)
    table.add_column("Price", justify="right", width=8)
    table.add_column("Status", style="yellow", width=14)

    for ev in events:
        ts = ev.get("ts", "")[:19].replace("T", " ").split(" ")[-1]
        kind = ev.get("event", "")
        market = ev.get("market") or ev.get("market_slug") or ev.get("event_title") or ""
        size = ev.get("size") or ev.get("size_usd") or ""
        if isinstance(size, (int, float)):
            size = f"{size:,.2f}"
        price = ev.get("price") or ev.get("yes_ask") or ev.get("yes_price") or ""
        if isinstance(price, (int, float)):
            price = f"{price:.4f}"
        status = ev.get("status") or ev.get("decision") or kind.split("_")[-1]
        table.add_row(ts, kind, str(market)[:40], str(size), str(price), str(status))
    return table


def main():
    if len(sys.argv) < 2:
        print("Usage: python dashboard.py <log-prefix>")
        print("Example: python dashboard.py logs/copy_v1")
        sys.exit(1)

    prefix = sys.argv[1]
    path = latest_log(prefix)
    if not path:
        print(f"No log found matching {prefix}-*.jsonl")
        sys.exit(1)
    print(f"Following {path}")

    events: deque = deque(maxlen=20)
    console = Console()
    with Live(render(events), console=console, refresh_per_second=2) as live:
        for line in follow(path):
            line = line.strip()
            if not line:
                continue
            try:
                ev = json.loads(line)
            except json.JSONDecodeError:
                continue
            events.append(ev)
            live.update(render(events))


if __name__ == "__main__":
    main()
