#!/usr/bin/env python3
"""Dump every FUT-hub route from one UTAS to a directory, for prod-vs-staging shape diffing.

Usage: dump_hub.py <port> <outdir>
"""
import json
import os
import socket
import sys

ROUTES = {
    "user_accountinfo": "/ut/game/fifa17/user/accountinfo",
    "squad_active": "/ut/game/fifa17/squad/active",
    "squad_0": "/ut/game/fifa17/squad/0",
    "club": "/ut/game/fifa17/club?count=20",
    "club_stats_staff": "/ut/game/fifa17/club/stats/staff",
    "club_stats_club": "/ut/game/fifa17/club/stats/club",
    "clientdata_store": "/ut/game/fifa17/clientdata/store",
    "purchased_items": "/ut/game/fifa17/purchased/items",
    "tradepile": "/ut/game/fifa17/tradePile",
    "tradepile_counts": "/ut/game/fifa17/tradePile/counts",
    "watchlist": "/ut/game/fifa17/watchList",
    "trade_status": "/ut/game/fifa17/trade/status",
    "usermassinfo": "/ut/game/fifa17/userMassInfo",
    "settings": "/ut/game/fifa17/settings",
}

port, outdir = int(sys.argv[1]), sys.argv[2]
os.makedirs(outdir, exist_ok=True)

for name, path in ROUTES.items():
    try:
        s = socket.create_connection(("127.0.0.1", port), timeout=25)
        s.sendall((f"GET {path} HTTP/1.1\r\nHost: x\r\n"
                   "X-OpenFUT-Game: fifa17\r\nConnection: close\r\n\r\n").encode())
        buf = b""
        while True:
            c = s.recv(65536)
            if not c:
                break
            buf += c
        s.close()
        head, _, body = buf.partition(b"\r\n\r\n")
        status = head.split(b" ")[1].decode()
        rec = {"status": status}
        try:
            rec["body"] = json.loads(body)
        except Exception:
            rec["body"] = None
            rec["raw"] = body[:200].decode(errors="replace")
        with open(os.path.join(outdir, f"{name}.json"), "w") as f:
            json.dump(rec, f)
        n = len(json.dumps(rec.get("body"))) if rec.get("body") is not None else 0
        print(f"  {status}  {name:<18} {n} bytes")
    except Exception as e:
        print(f"  ERR  {name:<18} {type(e).__name__}: {e}")
