#!/usr/bin/env python3
"""FanDuel props watch: keep a local record of every FanDuel player prop move, on a schedule.

Python 3.9+, standard library only. Reads your key from FANDUEL_API_KEY.

    mkdir -p ~/fanduel-watch && curl -fsSL https://fanduelapi.com/starter-kit/fanduel_props_watch.py -o ~/fanduel-watch/fanduel_props_watch.py
    FANDUEL_API_KEY=fd_... python3 ~/fanduel-watch/fanduel_props_watch.py --once

The first run saves the current board for your leagues to props.csv and starts the change feed from now. Every run
after that reads only what changed since the last one (GET /api/v1/changes with the saved cursor), appends each change
to changes.jsonl and moves.csv, and prints the line and price moves.

Run it on a schedule with --once (cron, launchd, a systemd timer, Task Scheduler or GitHub Actions; ready-made entries
at https://fanduelapi.com/docs/scheduled-jobs), or leave it running without --once and it polls every --every minutes.

It is careful with your allowance: one call (1 credit) per poll when nothing moved, a cap on pages per run, and after a 429 it
records when to try again and makes no request until then.

FanDuel API is an independent data service operated by Stunning Couches LLC. It is not affiliated with, endorsed by or sponsored
by FanDuel. The data is information, not betting advice.
"""
import argparse
import csv
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

BASE = "https://fanduelapi.com/api/v1"
VERSION = "1.0"
KEY_ENV = "FANDUEL_API_KEY"
MOVE_FIELDS = ["at", "kind", "league", "player", "stat", "period", "prev_line", "line",
               "prev_over", "over", "prev_under", "under", "prop_id", "event_id", "cursor"]
PROP_FIELDS = ["league", "player", "team", "stat", "period", "line", "over_american", "under_american", "market_status", "id", "event_id", "event_name", "starts_at"]


class Paused(Exception):
    """The API asked us to wait (429 or a next-update hint). until is epoch seconds."""

    def __init__(self, until, message):
        super().__init__(message)
        self.until = until


def now():
    return time.time()


def iso(ts):
    return datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def parse_time(value):
    try:
        return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
    except ValueError:
        return None


class Client:
    def __init__(self, key, purpose):
        self.key = key
        self.purpose = purpose
        self.calls = 0

    def get(self, path, **params):
        query = urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
        req = urllib.request.Request(f"{BASE}{path}{'?' + query if query else ''}", headers={
            "Authorization": f"Bearer {self.key}",
            "X-User-Request": self.purpose,
            "Accept": "application/json",
            "User-Agent": f"fanduel-props-watch/{VERSION} (python {sys.version_info[0]}.{sys.version_info[1]})",
        })
        self.calls += 1
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                body = json.loads(resp.read().decode("utf-8"))
                hint = resp.headers.get("X-Next-Update-Seconds")
                return body, (now() + float(hint)) if hint and hint.replace(".", "", 1).isdigit() else None
        except urllib.error.HTTPError as err:
            raw = err.read().decode("utf-8", "replace")
            try:
                error = json.loads(raw).get("error", {})
            except ValueError:
                error = {}
            if err.code == 429:
                until = parse_time(error.get("reset_at")) or now() + float(err.headers.get("Retry-After") or 60)
                raise Paused(until, error.get("user_message") or error.get("message") or "Rate limited.")
            if err.code in (401, 403):
                sys.exit(f"The API refused the key ({err.code}): {error.get('message', raw[:200])}. Check {KEY_ENV}.")
            raise RuntimeError(f"HTTP {err.code} on {path}: {error.get('message', raw[:300])}")



def load_state(path):
    try:
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError):
        return {}


def save_state(path, state):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=2)
    os.replace(tmp, path)


def append_csv(path, fields, rows):
    if not rows:
        return
    new = not os.path.exists(path) or os.path.getsize(path) == 0
    with open(path, "a", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        if new:
            w.writeheader()
        w.writerows(rows)


def first_run(client, leagues, out):
    """Save the current board for each league (one page of up to 200 props each) and start the feed from now."""
    rows = []
    for league in leagues:
        body, _ = client.get("/props", league=league, limit=200)
        rows += [{k: p.get(k) for k in PROP_FIELDS} for p in body.get("data", [])]
        print(f"{league}: {len(body.get('data', []))} props saved{' (first page; more on the board)' if body.get('meta', {}).get('has_more') else ''}")
    append_csv(os.path.join(out, "props.csv"), PROP_FIELDS, rows)
    body, hint = client.get("/changes", since="now")
    meta = body.get("meta", {})
    print(f"Change feed starts now. Plan {meta.get('plan')}, data delay {meta.get('delay_seconds')} s, {meta.get('remaining')} left this month.")
    return meta.get("next_cursor"), hint


def fmt(n):
    return "-" if n is None else (f"+{n}" if isinstance(n, int) and n > 0 else str(n))


def poll(client, cursor, leagues, out, max_pages):
    """Read every change after cursor, up to max_pages pages. Returns the new cursor and the next-update hint."""
    league = leagues[0] if len(leagues) == 1 else None
    wanted = {l.upper() for l in leagues}
    moves, raw, hint = [], [], None
    for _ in range(max_pages):
        body, hint = client.get("/changes", since=cursor, league=league, limit=100)
        meta = body.get("meta", {})
        for c in body.get("data", []):
            if wanted and str(c.get("league", "")).upper() not in wanted:
                continue
            raw.append(c)
            prev, cur = c.get("previous") or {}, c.get("current") or {}
            moves.append({"at": c.get("at"), "kind": c.get("kind"), "league": c.get("league"), "player": c.get("player"),
                          "stat": c.get("stat"), "period": c.get("period"), "prev_line": prev.get("line"), "line": cur.get("line"),
                          "prev_over": prev.get("over_american"), "over": cur.get("over_american"),
                          "prev_under": prev.get("under_american"), "under": cur.get("under_american"),
                          "prop_id": c.get("prop_id"), "event_id": c.get("event_id"), "cursor": c.get("cursor")})
        cursor = meta.get("next_cursor", cursor)
        # A short page means the rest is not readable yet (on a delayed plan has_more can be true while the newer
        # changes are still inside the delay), so stop and pick it up next run.
        if not meta.get("has_more") or len(body.get("data", [])) < 100:
            break
    if raw:
        with open(os.path.join(out, "changes.jsonl"), "a", encoding="utf-8") as f:
            f.writelines(json.dumps(c) + "\n" for c in raw)
        append_csv(os.path.join(out, "moves.csv"), MOVE_FIELDS, moves)
    for m in moves:
        if m["kind"] in ("line_move", "price_move"):
            line = f"{m['prev_line']} -> {m['line']}" if m["prev_line"] != m["line"] else f"{m['line']}"
            print(f"{m['at']}  {m['league']:<5} {str(m['player'])[:24]:<24} {str(m['stat'])[:12]:<12} {line:<14} "
                  f"o {fmt(m['prev_over'])}->{fmt(m['over'])}  u {fmt(m['prev_under'])}->{fmt(m['under'])}")
    other = len(moves) - sum(m["kind"] in ("line_move", "price_move") for m in moves)
    print(f"{iso(now())}  {len(moves)} changes ({other} new, suspended or removed), {client.calls} request(s).")
    return cursor, hint


def run_once(client, args, state_path):
    state = load_state(state_path)
    if args.resume:
        state.pop("paused_until", None)
        state.pop("paused_reason", None)
    wait = state.get("paused_until") or 0
    if wait > now():
        print(f"Waiting until {iso(wait)} as the API asked ({state.get('paused_reason', 'rate limit')}). No request made. After an upgrade, run once with --resume.")
        return wait
    leagues = [l.strip().upper() for l in args.league.split(",") if l.strip()]
    if state.get("leagues") and state["leagues"] != leagues:
        print(f"Leagues changed from {','.join(state['leagues'])}; starting the feed again.")
        state = {}
    try:
        if not state.get("cursor"):
            cursor, hint = first_run(client, leagues, args.dir)
        else:
            cursor, hint = poll(client, state["cursor"], leagues, args.dir, args.max_pages)
        state.update(cursor=cursor, leagues=leagues, last_run=iso(now()), paused_until=hint or 0)
        state.pop("paused_reason", None)
    except Paused as p:
        state.update(paused_until=p.until, paused_reason=str(p))
        print(f"The API asked to wait until {iso(p.until)}: {p}")
    save_state(state_path, state)
    return state.get("paused_until") or 0


def main():
    ap = argparse.ArgumentParser(description="Record every FanDuel player prop move. Run on a schedule with --once.")
    ap.add_argument("--league", default=os.environ.get("FANDUEL_LEAGUES", "NBA"),
                    help="Comma-separated leagues as FanDuel lists them, such as NBA,NFL,NHL (default NBA).")
    ap.add_argument("--dir", default=os.environ.get("FANDUEL_WATCH_DIR") or os.path.dirname(os.path.abspath(__file__)),
                    help="Where state.json, props.csv, moves.csv and changes.jsonl go (default: next to this script).")
    ap.add_argument("--once", action="store_true", help="Poll once and exit. Use this from cron, launchd, systemd or Task Scheduler.")
    ap.add_argument("--every", type=float, default=5, help="Minutes between polls when running without --once (default 5).")
    ap.add_argument("--resume", action="store_true", help="Forget a recorded wait, for example right after an upgrade.")
    ap.add_argument("--max-pages", type=int, default=5, help="Most pages of 500 changes to read per run (default 5).")
    ap.add_argument("--purpose", default="Scheduled job: record FanDuel player prop line and price moves",
                    help="Sent as X-User-Request: what this job is for, in one sentence.")
    args = ap.parse_args()
    key = os.environ.get(KEY_ENV, "").strip()
    if not key:
        sys.exit(f"Set {KEY_ENV} to your key from https://fanduelapi.com/dashboard/keys")
    os.makedirs(args.dir, exist_ok=True)
    state_path = os.path.join(args.dir, "state.json")
    client = Client(key, args.purpose)
    if args.once:
        run_once(client, args, state_path)
        return
    while True:
        client.calls = 0
        wait_until = run_once(client, args, state_path)
        time.sleep(max(args.every * 60, (wait_until or 0) - now(), 30))


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
    except RuntimeError as e:
        sys.exit(str(e))
