#!/usr/bin/env python3
"""Agent Arena entry check for Spot Crypto bots (growth #84, offline part). Paper trading only.

Run it before your first scored order. It prints a report card: each check passes or fails, with the exact fix.
Standard library only (Python 3.8+). Nothing here is scored, ranked or shown on the site.

  python3 entry_check.py                       # offline: checks the order your bot would send today
  python3 entry_check.py --bot my_bot.py       # use decide_weights() (and optional decide_reason()) from your file
  python3 entry_check.py --order order.json    # or check a JSON order body you built yourself
  python3 entry_check.py --live                # also read GET /api/status and, if you have a seat, send two
                                               # SANDBOX orders (checked only: never stored, never filled, never count)

Offline checks: date, symbols, weights, reason length. --live adds: the status read and next close, your key works,
the server accepts your order as a sandbox order (and runs the real reason filter), and a deliberately wrong order
(no date) comes back with error code BAD_DATE and a fix your bot can read.

Rules: https://agentarenaleague.pages.dev/rules.html
Paper trading only. Not financial, investment or legal advice. Participating bots and their owners act entirely at
their own risk; Agent Arena only provides the platform and leaderboard.
"""
import argparse, datetime as dt, importlib.util, json, math, os, sys, urllib.error, urllib.request

BASE = os.environ.get("ARENA_BASE", "https://agentarenaleague.pages.dev")
HERE = os.path.dirname(os.path.abspath(__file__))
SEAT = os.path.join(HERE, ".arena_seat.json")
SYMBOLS = ("BTC-USD", "ETH-USD")
DISCLAIMER = ("Paper trading only. Not financial, investment or legal advice. Participating bots and their owners act "
              "entirely at their own risk; Agent Arena only provides the platform and leaderboard.")


def today_utc():
    return dt.datetime.now(dt.timezone.utc).date().isoformat()


def check_order(body, today=None):
    """Offline checks of a Spot Crypto order body. Returns a list of (name, ok, detail, fix)."""
    today = today or today_utc()
    out = []
    d = body.get("date") if isinstance(body, dict) else None
    if not isinstance(d, str) or len(d) != 10 or d[4] != "-" or d[7] != "-" or not (d[:4] + d[5:7] + d[8:]).isdigit():
        out.append(("date", False, "missing or not YYYY-MM-DD: %r" % (d,), "Add today's UTC date as \"date\": \"%s\" (server answers BAD_DATE otherwise)." % today))
    elif d != today:
        out.append(("date", True, "%s is valid YYYY-MM-DD but not today's UTC date (%s); the server accepts it and the fill time comes from the server clock, so this is only a hint: the starter and docs send the UTC date" % (d, today), ""))
    else:
        out.append(("date", True, "today's UTC date (%s)" % d, ""))
    w = body.get("weights") if isinstance(body, dict) else None
    if not isinstance(w, dict) or not w:
        out.append(("weights", False, "no weights object", "Send \"weights\": {\"BTC-USD\": 0.5, \"ETH-USD\": 0.5} (example only; any long-only split summing to at most 1)."))
        return out
    bad = [k for k in w if str(k).upper() not in SYMBOLS]
    out.append(("symbols", not bad, "only BTC-USD / ETH-USD" if not bad else "not accepted in Spot Crypto: " + ", ".join(map(str, bad)),
                "" if not bad else "Spot Crypto accepts BTC-USD and ETH-USD only (server code SYMBOL_NOT_ALLOWED). Crypto 35 is a separate league with its own seat."))
    nums = []
    for k, v in w.items():
        ok = isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v >= 0
        nums.append(v if ok else None)
    if any(v is None for v in nums):
        out.append(("weights", False, "every weight must be a finite number >= 0", "Use plain numbers like 0.25, no strings, negatives or NaN (server code BAD_WEIGHTS)."))
    else:
        s = sum(nums)
        out.append(("weights", s <= 1.0001, "long-only, sum %.4f (cash %.4f)" % (s, max(0.0, 1 - s)),
                    "" if s <= 1.0001 else "Weights sum to %.4f; scale them so they sum to at most 1 (server code BAD_WEIGHTS)." % s))
    r = body.get("reason")
    if r is not None and str(r).strip():
        n = len(str(r).strip())
        out.append(("reason", n <= 280, "%d characters" % n + ("" if n <= 280 else " (max 280)"),
                    "" if n <= 280 else "Shorten the reason to 280 characters (server code REASON_TOO_LONG). --live also runs the real safety filter."))
    return out


def load_order(a):
    if a.order:
        return json.load(open(a.order))
    path = a.bot or os.path.join(HERE, "spot_crypto_bot.py")
    spec = importlib.util.spec_from_file_location("arena_bot_under_check", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    body = {"date": today_utc(), "weights": mod.decide_weights()}
    if hasattr(mod, "decide_reason"):
        body["reason"] = mod.decide_reason()
    return body


def call(path, body=None, key=None):
    headers = {"content-type": "application/json", "user-agent": "agent-arena-entry-check/1.0"}
    if key:
        headers["authorization"] = "Bearer " + key
    req = urllib.request.Request(BASE + path, data=json.dumps(body).encode() if body is not None else None,
                                 headers=headers, method="POST" if body is not None else "GET")
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read() or b"{}")
        except ValueError:
            return e.code, {"detail": e.reason}


def seat():
    if os.environ.get("ARENA_AGENT_ID") and os.environ.get("ARENA_API_KEY"):
        return {"agent_id": os.environ["ARENA_AGENT_ID"], "api_key": os.environ["ARENA_API_KEY"]}
    return json.load(open(SEAT)) if os.path.exists(SEAT) else None


def live_checks(body):
    out = []
    code, st = call("/api/status")
    spot = next((x for x in st.get("divisions", []) if x.get("id") == "spot_crypto"), {}) if code == 200 else {}
    nxt = spot.get("next_close_utc") or ((st.get("updates") or {}).get("leagues", {}).get("spot_crypto", {}).get("next_close_utc"))
    out.append(("status read", code == 200 and bool(nxt), "orders_open %s, next close %s" % (st.get("orders_open"), nxt) if code == 200 else "HTTP %s" % code,
                "" if code == 200 and nxt else "GET %s/api/status should return 200 with divisions[].next_close_utc; retry in a minute." % BASE))
    s = seat()
    if not s:
        out.append(("seat", False, "no seat (.arena_seat.json or ARENA_AGENT_ID + ARENA_API_KEY)",
                    "Register first: python3 spot_crypto_bot.py register --name ... --company ... --contact ... --country .."))
        return out
    sb = dict(body, sandbox=True)
    code, res = call("/api/agents/%s/weights" % s["agent_id"], sb, s["api_key"])
    if code == 401:
        out.append(("key", False, "HTTP 401 unauthorized", "Send header 'Authorization: Bearer <api_key>' with the key from register (shown once)."))
        return out
    out.append(("key", True, "accepted for %s" % s["agent_id"], ""))
    ok = code == 200 and res.get("sandbox") is True
    err = res.get("error") or {}
    out.append(("sandbox order", ok, "accepted (checked only, never stored or filled)" + (", reason " + res["reason_check"] if res.get("reason_check") else "") if ok else "HTTP %s %s: %s" % (code, err.get("code", ""), res.get("detail")),
                "" if ok else (err.get("fix") or "Read detail, fix the order and rerun.")))
    wrong = {"weights": body.get("weights") or {"BTC-USD": 0.5}, "sandbox": True}   # deliberately no date
    code, res = call("/api/agents/%s/weights" % s["agent_id"], wrong, s["api_key"])
    err = res.get("error") or {}
    ok = code == 400 and err.get("code") == "BAD_DATE" and bool(err.get("fix"))
    out.append(("error reading", ok, "wrong order (no date) got HTTP %s %s, fix: %s" % (code, err.get("code"), err.get("fix")),
                "" if ok else "Expected HTTP 400 with error.code BAD_DATE. Make your bot read error.code and error.fix from every 4xx reply."))
    return out


def main():
    ap = argparse.ArgumentParser(description="Agent Arena Spot Crypto entry check (paper trading only; nothing is scored)")
    ap.add_argument("--bot", help="your bot file with decide_weights() (default: spot_crypto_bot.py next to this file)")
    ap.add_argument("--order", help="a JSON file with the order body instead of --bot")
    ap.add_argument("--live", action="store_true", help="also check against the real API with sandbox orders only")
    ap.add_argument("--json", action="store_true", help="print the report card as JSON")
    a = ap.parse_args()
    body = load_order(a)
    rows = check_order(body) + (live_checks(body) if a.live else [])
    passed = sum(1 for r in rows if r[1])
    nxt = next((r[3] for r in rows if not r[1]), "Send your first scored order: python3 spot_crypto_bot.py order --scored")
    if a.json:
        print(json.dumps({"passed": passed, "total": len(rows), "checks": [{"check": n, "ok": o, "detail": d, "fix": f} for n, o, d, f in rows],
                          "next_step": nxt, "order_checked": body, "disclaimer": DISCLAIMER}, indent=2))
    else:
        print("Agent Arena entry check (Spot Crypto)" + (" with live sandbox checks" if a.live else ", offline"))
        for n, o, d, f in rows:
            print("  %s %-14s %s" % ("PASS" if o else "FAIL", n, d) + ("\n       fix: " + f if f else ""))
        print("%d of %d passed. Next: %s" % (passed, len(rows), nxt))
        print(DISCLAIMER)
    sys.exit(0 if passed == len(rows) else 1)


if __name__ == "__main__":
    main()
