import requests, json, re, os, shutil, glob
from datetime import datetime

# EOJHL standings feed (JSONP)
STANDINGS_URL = (
    "https://lscluster.hockeytech.com/feed/index.php?"
    "feed=statviewfeed&view=teams&groupTeamsBy=division&context=overall"
    "&site_id=2&season=110&special=false&key=1defb601c9b37c24"
    "&client_code=eojhl&league_id=2&conference=-1&division=-1"
    "&sort=points&lang=en&callback=angular.callbacks._4"
)

# --- TEAM ABBREVIATION MAP ---
TEAM_ABBR_MAP = {
    "Ottawa": "OJC",
    "Carleton Place": "CPC",
    "Ottawa West": "OTW",
    "Richmond": "RCH",
    "Casselman": "CAS",
    "Smiths Falls": "SFB",
    "Embrun": "EMB",
    "Perth": "PER",
    "Glengarry": "GB",
    "Arnprior": "ARP",
    "Athens": "ATH",
    "Renfrew": "REN",
    "Winchester": "WIN"
}

OUTPUT_FILE = "eojhl_standings.json"
MAX_BACKUPS = 2

def backup_file(filename):
    """Backup existing file with timestamp and prune old backups."""
    if os.path.exists(filename):
        ts = datetime.now().strftime("%Y%m%d-%H%M%S")
        backup = f"{filename}.{ts}.bak"
        shutil.move(filename, backup)
        backups = sorted(glob.glob(f"{filename}.*.bak"), reverse=True)
        for old in backups[MAX_BACKUPS:]:
            os.remove(old)
        print(f"Backed up {filename} -> {backup}")

def fetch_jsonp(url):
    """Fetch JSONP and return parsed JSON (handles arrays or objects)."""
    text = requests.get(url).text.strip()
    if text.startswith("{") or text.startswith("["):
        return json.loads(text)
    match = re.search(r'^[^(]+\((.*)\)\s*$', text, re.S)
    if match:
        return json.loads(match.group(1))
    raise ValueError("Response was not valid JSON or JSONP:\n" + text[:200])

def transform_standings(raw):
    """Transform HockeyTech standings into legacy JSON format with records."""
    standings = {"martin": [], "richardson": []}
    sections = raw[0].get("sections", [])
    for section in sections:
        headers = section.get("headers", {})
        label = headers.get("name", {}).get("properties", {}).get("label", "").lower()
        key = "martin" if "martin" in label else "richardson" if "richardson" in label else None
        if not key:
            continue
        for team in section.get("data", []):
            row = team.get("row", {})
            name = row.get("name", "").strip()
            if not name:
                continue
            abbr = row.get("team_code") or name[:3].upper()

            # Extract record fields (keys may vary: wins, losses, ties, ot_losses, shootout_losses)
            wins = row.get("wins", "0")
            losses = row.get("losses", "0")
            ot_losses = row.get("ot_losses") or int("0")
            so_losses = row.get("shootout_losses") or int("0")
            otlosses = int(ot_losses) + int(so_losses)
            record = f"{wins}-{losses}-{otlosses}"

            standings[key].append({
                "name": name,
                "abbreviation": abbr,
                "logo": f"assets/sports/eojhl_logos/{abbr}.png",
                "record": record
            })
    return standings

if __name__ == "__main__":
    backup_file(OUTPUT_FILE)
    raw = fetch_jsonp(STANDINGS_URL)
    standings = transform_standings(raw)
    with open(OUTPUT_FILE, "w") as f:
        json.dump(standings, f, indent=2)
    print(f"Standings written to {OUTPUT_FILE}")
