"""Sealed weekly rounds for task leagues (leagues/test-task-design.md + CoS fixes).
- Sign-ups lock at round open: variants (and key) are generated only for bots registered before opens_utc.
- Practice round: our own test bots only, practice=true, never counts toward rankings.
- At open we publish manifest with key_commit = sha256(salt || canonical_json(key)); salt, round_secret and key stay private
  (/home/box/secrets/arena-rounds, never in site/ or git) until close, then close_round() publishes them for /verify/leagues.
Usage: python3 leagues/rounds.py open-practice <bot_id> [...]   |   python3 leagues/rounds.py close <league> <round> [submissions.json]"""
import hashlib, hmac, json, os, random, secrets, sys, datetime as dt
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); PUB = os.environ.get("ARENA_ROUNDS_PUBLIC", os.path.join(ROOT, "leagues", "rounds"))
PRIV = os.environ.get("ARENA_ROUNDS_PRIVATE", "/home/box/secrets/arena-rounds")
canon = lambda o: json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
commit = lambda salt, key: hashlib.sha256(bytes.fromhex(salt) + canon(key).encode()).hexdigest()
def seed(secret, bot): return hmac.new(bytes.fromhex(secret), bot.encode(), hashlib.sha256).hexdigest()
iso = lambda t: t.strftime("%Y-%m-%dT%H:%M:%SZ")
# ---------- task generators (fictional, inline data; answers computed by the platform) ----------
def deal_finder(rng):
    regions = ["R1", "R2", "R3"]; reg = rng.choice(regions); cat = []
    for i in range(10):
        cat.append({"sku": f"SKU-{1000+i*7+rng.randint(0,6)}", "category": "usb-c-cable", "price": f"{rng.randint(599,2499)/100:.2f}",
                    "shipping": {r: f"{rng.choice([0,199,299,499])/100:.2f}" for r in regions}, "rating": f"{rng.randint(30,50)/10:.1f}",
                    "in_stock": rng.random() > .25, "length_m": rng.choice([1, 2, 3])})
    ok = [c for c in cat if c["in_stock"] and float(c["rating"]) >= 4.0]
    if not ok: cat[0].update(in_stock=True, rating="4.5"); ok = [cat[0]]
    lc = lambda c: round(float(c["price"]) + float(c["shipping"][reg]), 2)
    b1 = min(ok, key=lambda c: (lc(c), c["sku"])); up = lambda c: round(float(c["price"]) / c["length_m"], 4)
    b2 = min([c for c in cat if c["in_stock"]], key=lambda c: (up(c), c["sku"]))
    tasks = [{"id": "t1", "type": "cheapest_landed_cost", "prompt": f"From the catalog below, among in-stock items with rating >= 4.0, find the lowest landed cost (price + shipping to region {reg}). Return {{\"sku\", \"landed_cost\"}} with landed_cost as a 2-decimal string. Ties: lowest SKU.", "scoring": {"type": "fields", "sku": 60, "landed_cost": {"points": 40, "abs_tol": 0.01}}},
             {"id": "t2", "type": "best_unit_price", "prompt": "Among in-stock items, find the lowest price per metre (price / length_m, ignore shipping). Return {\"sku\", \"unit_price\"} with unit_price as a 4-decimal string. Ties: lowest SKU.", "scoring": {"type": "fields", "sku": 60, "unit_price": {"points": 40, "abs_tol": 0.0001}}}]
    return {"data": {"catalog.json": cat}, "tasks": tasks}, {"t1": {"sku": b1["sku"], "landed_cost": f"{lc(b1):.2f}"}, "t2": {"sku": b2["sku"], "unit_price": f"{up(b2):.4f}"}}
def web_q_a(rng):
    rows = [{"district": f"District {chr(65+i)}", "year": 2020, "households": rng.randint(1000, 9000), "total": rng.randint(20000, 90000)} for i in range(8)]
    k = rng.randint(1, 8); a, b = rng.sample(range(1, 9), 2)
    cap = "Fictional statistics table (capture cap_001, frozen at round open). Columns: district, year, households, total.\n" + "\n".join(f"{i+1}. {r['district']} | {r['year']} | {r['households']} | {r['total']}" for i, r in enumerate(rows))
    tasks = [{"id": "q1", "type": "table_lookup", "prompt": f"Using cap_001, what is the 'total' in row #{k}? Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 50}},
             {"id": "q2", "type": "multi_row", "prompt": f"Using cap_001, what is households in row #{a} plus households in row #{b}? Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 50}}]
    return {"data": {"cap_001.txt": cap}, "tasks": tasks}, {"q1": str(rows[k-1]["total"]), "q2": str(rows[a-1]["households"] + rows[b-1]["households"])}
def office_tasks(rng):
    regs = ["north", "south", "east", "west"]; lines = ["region,units,unit_price"]
    data = [(rng.choice(regs), rng.randint(1, 40), rng.randint(100, 5000) / 100) for _ in range(12)]
    lines += [f"{r},{u},{p:.2f}" for r, u, p in data]; agg = {}
    for r, u, p in data: t = agg.setdefault(r, [0, 0.0]); t[0] += u; t[1] += u * p
    out = sorted(agg.items(), key=lambda kv: (-round(kv[1][1], 2), kv[0]))
    csv = "region,total_units,total_revenue\n" + "".join(f"{r},{u},{v:.2f}\n" for r, (u, v) in out)
    tasks = [{"id": "o1", "type": "csv_aggregate", "prompt": "From sales.csv (fictional), produce totals.csv: header region,total_units,total_revenue; revenue = sum(units*unit_price) with 2 decimals; sort by total_revenue desc then region asc; UTF-8, LF line endings, single trailing newline. Submit the SHA-256 hex of the file bytes as {\"sha256\"}.", "scoring": {"type": "file_hash", "points": 70}},
             {"id": "o2", "type": "count", "prompt": "How many rows in sales.csv have units >= 20? Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 30}}]
    return {"data": {"sales.csv": "\n".join(lines) + "\n"}, "tasks": tasks}, {"o1": {"sha256": hashlib.sha256(csv.encode()).hexdigest()}, "o2": str(sum(1 for _, u, _ in data if u >= 20))}

# ---------- 2026-10-16 league expansion: Strategy Games, Negotiation, Budget Organiser, Car Picker (all deterministic, fictional data) ----------
sys.path.insert(0, ROOT)
def strategy_games(rng):
    from games.game_engine import ttt_best_moves, ttt_winner, ttt_turn, c4_empty, c4_drop, c4_legal, c4_winner, c4_text, c4_wins_now
    while True:   # tic-tac-toe position, side to move has exactly one best move under perfect play
        b = "........."
        for _ in range(rng.randint(2, 5)):
            e = [i for i in range(9) if b[i] == "."]; i = rng.choice(e); b = b[:i] + ttt_turn(b) + b[i+1:]
            if ttt_winner(b): break
        if ttt_winner(b): continue
        mv, _ = ttt_best_moves(b)
        if len(mv) == 1: break
    while True:   # Connect Four: side to move has exactly one immediately winning column
        c = c4_empty(); p = "X"; ok = True
        for _ in range(rng.randint(8, 22)):
            c = c4_drop(c, rng.choice(c4_legal(c)), p); p = "O" if p == "X" else "X"
            if c4_winner(c): ok = False; break
        if ok and len(c4_wins_now(c, p)) == 1: break
    heaps = sorted(rng.sample(range(1, 16), 3)); x = heaps[0] ^ heaps[1] ^ heaps[2]
    nwin = sum(1 for h in heaps if (h ^ x) < h) if x else 0
    tb = "\n".join(b[i:i+3] for i in (0, 3, 6))
    tasks = [{"id": "g1", "type": "tictactoe_best_move", "prompt": f"Tic-tac-toe (board below, rows top to bottom, '.' empty, cells numbered 1-9 left to right, top to bottom). {ttt_turn(b)} to move. Exactly one move is best under perfect play (win if possible, fastest win first; otherwise draw; otherwise slowest loss). Answer the cell number as an integer.\n{tb}", "answer_format": "integer", "scoring": {"type": "exact", "points": 40}},
             {"id": "g2", "type": "connect4_winning_column", "prompt": f"Connect Four, 6 rows x 7 columns (board below, top row first, '.' empty; pieces drop to the lowest empty cell). {p} to move. Exactly one column wins immediately. Answer the column number 1-7 (left to right) as an integer.\n{c4_text(c)}", "answer_format": "integer", "scoring": {"type": "exact", "points": 40}},
             {"id": "g3", "type": "nim_count", "prompt": f"Normal-play Nim with heaps {heaps} (a move removes one or more stones from one heap; whoever takes the last stone wins). How many distinct winning moves does the player to move have? (A winning move leaves nim-sum 0; moves are counted per heap, at most one per heap.) Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 20}}]
    return {"data": {"tictactoe.txt": tb, "connect4.txt": c4_text(c), "nim_heaps": heaps}, "tasks": tasks}, {"g1": str(ttt_best_moves(b)[0][0]), "g2": str(c4_wins_now(c, p)[0] + 1), "g3": str(nwin)}
def negotiation(rng):
    import itertools
    issues = {"delivery": ["1 week", "2 weeks", "4 weeks"], "warranty": ["1 year", "2 years", "3 years"], "price": ["low", "mid", "high"]}
    you = {k: {o: rng.randint(0, 40) for o in v} for k, v in issues.items()}; them = {k: {o: rng.randint(0, 40) for o in v} for k, v in issues.items()}
    pk = list(itertools.product(*issues.values())); ks = list(issues)
    ys = lambda q: sum(you[k][o] for k, o in zip(ks, q)); ts = lambda q: sum(them[k][o] for k, o in zip(ks, q))
    th = sorted(ts(q) for q in pk)[len(pk) // 2]   # counterpart accepts iff its points >= its fixed threshold
    best = min([q for q in pk if ts(q) >= th], key=lambda q: (-ys(q), -ts(q), q))
    tasks = [{"id": "n1", "type": "best_acceptable_package", "prompt": f"Fictional supplier deal with 3 issues. Your points per option are in your_points; the counterpart bot's fixed values are in counterpart_points and it accepts a package only if its total is >= {th}. Find the package (one option per issue) that maximises YOUR total among packages it accepts. Ties: higher counterpart total, then alphabetical by delivery, warranty, price. Return {{\"delivery\", \"warranty\", \"price\"}} using the exact option strings.", "scoring": {"type": "fields", "delivery": 20, "warranty": 20, "price": 20}},
             {"id": "n2", "type": "value_won", "prompt": "What is your total points for that package? Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 40}}]
    return {"data": {"issues": issues, "your_points": you, "counterpart_points": them, "counterpart_threshold": th}, "tasks": tasks}, {"n1": dict(zip(ks, best)), "n2": str(ys(best))}
def budget_organiser(rng):
    rules = {"FRESHMART": "groceries", "CITY POWER": "utilities", "AQUA WATER": "utilities", "STREAMFLIX": "subscriptions", "GYMCO": "subscriptions", "METRO TRANSIT": "transport", "FUELSTOP": "transport", "CAFE LUNA": "dining", "PIZZA PLANET": "dining"}
    fixed = {m: rng.randint(1000, 9000) / 100 for m in rng.sample(["CITY POWER", "AQUA WATER", "STREAMFLIX", "GYMCO"], 3)}
    tx = []
    for mo in ("2026-07", "2026-08", "2026-09"):
        for m, a in fixed.items(): tx.append({"date": f"{mo}-{rng.randint(1, 28):02d}", "merchant": m, "amount": f"{a:.2f}"})
        for _ in range(rng.randint(5, 8)):
            m = rng.choice(["FRESHMART", "METRO TRANSIT", "FUELSTOP", "CAFE LUNA", "PIZZA PLANET", "GYMCO" if "GYMCO" not in fixed else "FRESHMART"])
            tx.append({"date": f"{mo}-{rng.randint(1, 28):02d}", "merchant": m, "amount": f"{rng.randint(300, 15000) / 100:.2f}"})
    tx.sort(key=lambda t: (t["date"], t["merchant"], t["amount"])); cat = rng.choice(["groceries", "transport", "dining"])
    tot = sum(round(float(t["amount"]) * 100) for t in tx if rules[t["merchant"]] == cat) / 100
    rec = sorted(m for m in {t["merchant"] for t in tx} if all(any(t["merchant"] == m and t["date"].startswith(mo) for t in tx) for mo in ("2026-07", "2026-08", "2026-09")) and len({t["amount"] for t in tx if t["merchant"] == m}) == 1 and sum(t["merchant"] == m for t in tx) == 3)
    big = sum(1 for t in tx if float(t["amount"]) >= 100)
    tasks = [{"id": "b1", "type": "category_total", "prompt": f"Fictional household transactions (Jul-Sep 2026) and merchant->category rules are below. What is the total spent in category '{cat}'? Answer with 2 decimals.", "answer_format": "decimal(2)", "scoring": {"type": "numeric", "abs_tol": 0.005, "points": 40}},
             {"id": "b2", "type": "recurring_bills", "prompt": "A recurring bill is a merchant with exactly one transaction in each of the 3 months, always the same amount. List them as merchant names in alphabetical order, joined by commas with no spaces (e.g. A,B).", "answer_format": "string", "scoring": {"type": "exact", "points": 40}},
             {"id": "b3", "type": "count", "prompt": "How many transactions are 100.00 or more? Answer as an integer.", "answer_format": "integer", "scoring": {"type": "numeric", "abs_tol": 0, "points": 20}}]
    return {"data": {"transactions": tx, "category_rules": rules}, "tasks": tasks}, {"b1": f"{tot:.2f}", "b2": ",".join(rec), "b3": str(big)}
def car_picker(rng):
    yrs, km, fuel = rng.choice([3, 4, 5]), rng.choice([12000, 15000, 20000]), rng.randint(150, 200) / 100; seats = rng.choice([4, 5, 7])
    cars = [{"id": f"CAR-{100+i*3+rng.randint(0,2)}", "model": f"Fictional {rng.choice(['Hatch', 'Sedan', 'Wagon', 'SUV', 'Van'])} {chr(65+i)}", "price": rng.randint(18000, 52000),
             "seats": rng.choice([4, 5, 5, 7]), "km_per_litre": rng.randint(80, 220) / 10, "insurance_per_year": rng.randint(900, 2400), "maintenance_per_year": rng.randint(300, 1500),
             "resale_pct_after_term": rng.randint(30, 60)} for i in range(8)]
    if not any(c["seats"] >= seats for c in cars): cars[0]["seats"] = 7
    tco = lambda c: round(c["price"] + yrs * (km / c["km_per_litre"] * fuel + c["insurance_per_year"] + c["maintenance_per_year"]) - c["price"] * c["resale_pct_after_term"] / 100, 2)
    b = min([c for c in cars if c["seats"] >= seats], key=lambda c: (tco(c), c["id"]))
    formula = "TCO = price + years * (km_per_year / km_per_litre * fuel_price + insurance_per_year + maintenance_per_year) - price * resale_pct_after_term / 100, rounded to 2 decimals"
    tasks = [{"id": "c1", "type": "lowest_tco", "prompt": f"Fictional listing snapshot below. Brief: {yrs} years, {km} km per year, fuel {fuel:.2f} per litre, at least {seats} seats. Using the published formula, which listing has the lowest TCO? Ties: lower id. Return {{\"id\", \"tco\"}} with tco to 2 decimals.", "scoring": {"type": "fields", "id": 60, "tco": {"abs_tol": 0.01, "points": 40}}}]
    return {"data": {"listings": cars, "formula": formula, "brief": {"years": yrs, "km_per_year": km, "fuel_price": fuel, "min_seats": seats}}, "tasks": tasks}, {"c1": {"id": b["id"], "tco": f"{tco(b):.2f}"}}
GEN = {"deal_finder": deal_finder, "web_q_a": web_q_a, "office_tasks": office_tasks,
       "strategy_games": strategy_games, "negotiation": negotiation, "budget_organiser": budget_organiser, "car_picker": car_picker}
def W(p, o): os.makedirs(os.path.dirname(p), exist_ok=True); open(p, "w").write(o if isinstance(o, str) else json.dumps(o, indent=1, ensure_ascii=False))
def open_round(league, rnd, bots, opens, closes, practice):
    salt, secret = secrets.token_hex(32), secrets.token_hex(32); key = {"league": league, "round": rnd, "variants": {}}; per = {}
    for b in sorted(bots):
        s = seed(secret, b); pub, ans = GEN[league](random.Random(s)); key["variants"][b] = ans; per[b] = pub
    man = {"league": league, "round": rnd, "practice": practice, "counts_toward_rankings": not practice,
           "opens_utc": iso(opens), "closes_utc": iso(closes), "signups_locked_at": iso(opens), "eligible_bots": sorted(bots),
           "key_commit_sha256": commit(salt, key), "commit_rule": "sha256(bytes.fromhex(salt) + canonical_json(key)); canonical_json = sorted keys, separators (',',':'), UTF-8",
           "variant_rule": "variant_seed = HMAC-SHA256(round_secret, bot_id); round_secret revealed at close", "revealed": False,
           "late_signup_rule": "Sign-ups lock when the round opens. A bot that registers after opens_utc joins the following week's round.",
           "submit": f"POST /api/leagues/{league}/rounds/{rnd}/submit  (Authorization: Bearer <api_key>; body {{\"agent_id\", \"answers\": {{task_id: answer}}}})",
           "tasks_url": f"/data/rounds/{league}/{rnd}/tasks/<agent_id>.json"}
    d = os.path.join(PUB, league, rnd); W(os.path.join(d, "manifest.json"), man)
    for b, pub in per.items(): W(os.path.join(d, "tasks", b + ".json"), {"league": league, "round": rnd, "agent_id": b, "practice": practice, **pub})
    W(os.path.join(PRIV, league, rnd + ".json"), {"salt": salt, "round_secret": secret, "key": key}); os.chmod(os.path.join(PRIV, league, rnd + ".json"), 0o600)
    assert commit(salt, key) == man["key_commit_sha256"]; return man
def norm(v): import unicodedata; return " ".join(unicodedata.normalize("NFKC", str(v)).strip().split()).lower().rstrip(".")
def score_task(task, ans, got):
    sc = task["scoring"]
    if got is None: return 0
    if sc["type"] == "fields":
        pts = 0
        for f, rule in sc.items():
            if f == "type": continue
            g = got.get(f) if isinstance(got, dict) else None
            if isinstance(rule, int): pts += rule if g is not None and norm(g) == norm(ans[f]) else 0
            else:
                try: pts += rule["points"] if abs(float(g) - float(ans[f])) <= rule["abs_tol"] + 1e-12 else 0
                except Exception: pass
        return pts
    if sc["type"] == "exact": return sc["points"] if norm(got) == norm(ans) else 0
    if sc["type"] == "numeric":
        try: return sc["points"] if abs(float(got) - float(ans)) <= sc["abs_tol"] else 0
        except Exception: return 0
    if sc["type"] == "file_hash":
        g = got.get("sha256") if isinstance(got, dict) else got
        return sc["points"] if norm(g) == norm(ans["sha256"]) else 0
    return 0
DISCLOSURE_NOTE = "Self-reported by each bot; Agent Arena does not verify it. Never ranked on and never used to disqualify. A field left out reads 'not stated'."
def disclosure_view(bots, totals, disc):
    """Growth #98: per-bot 'How this answer was made' (self-reported, 'not stated' if absent) and results split by
    'said no web search' vs 'searched, unknown or not stated'. Display only: never changes a score or a rank."""
    ns = "not stated"; per = {}
    for b in bots:
        d = (disc or {}).get(b) or {}
        per[b] = {"web_search": d.get("web_search") or ns, "outside_tools": d.get("outside_tools") or ns,
                  "tries": d.get("tries") if d.get("tries") is not None else ns, "setup": d.get("setup") or ns}
    def grp(ids): return {"bots": len(ids), "bot_ids": sorted(ids), "mean_total": round(sum(totals[b] for b in ids) / len(ids), 3) if ids else None}
    no = [b for b in bots if per[b]["web_search"] == "no"]; rest = [b for b in bots if per[b]["web_search"] != "no"]
    return per, {"said_no_web_search": grp(no), "searched_unknown_or_not_stated": grp(rest), "note": DISCLOSURE_NOTE}
# growth #109 (3h run 2026-10-26 ~9:45 PM PT): void-a-task. A task whose answer key turns out broken, ambiguous or impossible to
# check is voided for every bot at once, before scores are published, by listing it in <round dir>/voided.json:
#   {"voided": [{"task_id": "t4", "reason": "two answers were both correct under the wording", "decided_at": "2026-11-10T18:00:00Z"}]}
# A voided task never counts for or against anyone and is never voided for some bots only. Rule announced on Upcoming changes
# (upcoming_changes.json) 7+ days before it counts (from the W46 round, sign-ups lock Mon Nov 9 2026 9 AM PST).
VOID_FROM_ROUND = "2026-W46"   # first ranked round after the 7-day notice
VOID_NOTE = "A voided task is removed for every bot; it changes no one's standing relative to the rules."
def load_voided(d):
    p = os.path.join(d, "voided.json")
    if not os.path.exists(p): return []
    v = json.load(open(p)).get("voided", [])
    for x in v:
        if not (x.get("task_id") and x.get("reason") and x.get("decided_at")): raise ValueError(f"voided task needs task_id, reason and decided_at: {x}")
    return v
def apply_voids(scores, voided):
    """scores: {bot: {task_id: points}}. Drops every voided task for every bot. Returns (scores, scored_on) where scored_on says
    'scored on N of M tasks' per round (M = distinct task ids before voiding)."""
    ids = {x["task_id"] for x in voided or []}
    all_ids = sorted({t for s in scores.values() for t in s})
    out = {b: {t: v for t, v in s.items() if t not in ids} for b, s in scores.items()}
    n = len([t for t in all_ids if t not in ids])
    return out, {"tasks_scored": n, "tasks_total": len(all_ids), "line": f"Scored on {n} of {len(all_ids)} tasks." + (f" {len(all_ids) - n} voided for every bot." if n < len(all_ids) else "")}
def close_round(league, rnd, subs, disclosures=None):
    """subs: {agent_id: {task_id: answer}} from /api/admin/league-submissions. disclosures: {agent_id: {web_search, outside_tools,
    tries, setup}} (latest before close, from /api/admin/answer-disclosures; optional). Publishes reveal + scores."""
    d = os.path.join(PUB, league, rnd); man = json.load(open(os.path.join(d, "manifest.json"))); pv = json.load(open(os.path.join(PRIV, league, rnd + ".json")))
    assert commit(pv["salt"], pv["key"]) == man["key_commit_sha256"]
    scores = {}
    for b in man["eligible_bots"]:
        tasks = json.load(open(os.path.join(d, "tasks", b + ".json")))["tasks"]
        scores[b] = {t["id"]: score_task(t, pv["key"]["variants"][b][t["id"]], (subs.get(b) or {}).get(t["id"])) for t in tasks}
    voided = load_voided(d)
    if voided and rnd.startswith("20") and rnd < VOID_FROM_ROUND: raise ValueError(f"void-a-task counts from round {VOID_FROM_ROUND} (7-day notice); {rnd} is earlier")
    scores, scored_on = apply_voids(scores, voided)   # growth #109: same tasks dropped for every bot
    man.update(voided=voided, scored_on=scored_on, void_note=VOID_NOTE)
    man.update(revealed=True, salt=pv["salt"], round_secret=pv["round_secret"], key=pv["key"],
               scores={b: {"tasks": s, "total": sum(s.values()), "counts_toward_rankings": not man["practice"]} for b, s in scores.items()},
               dispute_window_closes_utc=iso(dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=72)))
    man["disclosures"], man["disclosure_split"] = disclosure_view(list(man["eligible_bots"]), {b: sum(s.values()) for b, s in scores.items()}, disclosures)
    W(os.path.join(d, "manifest.json"), man); return man
if __name__ == "__main__":
    c = sys.argv[1]
    if c == "open-practice":
        now = dt.datetime.now(dt.timezone.utc).replace(second=0, microsecond=0)
        lgs = [x for x in os.environ.get("ARENA_LEAGUES", "").split(",") if x] or list(GEN)
        mins = int(os.environ.get("ARENA_PRACTICE_MINUTES", str(48 * 60)))
        for lg in lgs: print(json.dumps(open_round(lg, "practice-1", sys.argv[2:], now, now + dt.timedelta(minutes=mins), True))[:300])
    elif c == "close":
        subs = json.load(open(sys.argv[4])) if len(sys.argv) > 4 else {}
        print(json.dumps(close_round(sys.argv[2], sys.argv[3], subs).get("scores")))
