#!/usr/bin/env python3 import argparse import os import sys import requests def fetch_json(api_root, path): url = f"{api_root}{path}" resp = requests.get(url, timeout=30) resp.raise_for_status() return resp.json() def main(): parser = argparse.ArgumentParser( description="Populate a local instance from production data via REST" ) parser.add_argument( "--source", default=os.environ.get("PHENIX_SOURCE_URL", "https://ballephenix.com"), help="Source API root (default: https://ballephenix.com)", ) parser.add_argument( "--target", default=os.environ.get("PHENIX_TARGET_URL", "http://localhost:5000"), help="Target API root (default: http://localhost:5000)", ) parser.add_argument( "--force", action="store_true", help="Clear existing games before inserting", ) args = parser.parse_args() source_root = args.source.rstrip("/") target_root = args.target.rstrip("/") years = fetch_json(source_root, "/api/available-years.json") print(f"Years on source: {len(years)} ({min(years)}–{max(years)})") all_games = [] for year in years: games = fetch_json(source_root, f"/api/results/{year}.json") all_games.extend(games) print(f"Total games fetched: {len(all_games)}") if args.force: resp = requests.delete(f"{target_root}/api/games", timeout=30) if resp.status_code not in (204, 200): print(f"Failed to clear games: {resp.status_code} {resp.text}", file=sys.stderr) sys.exit(1) print("Cleared existing games") inserted = 0 skipped = 0 errors = 0 for g in all_games: payload = { "date": g.get("date", ""), "time": g.get("time", ""), "home": g.get("home", ""), "away": g.get("away", ""), "homeScore": g.get("homeScore"), "awayScore": g.get("awayScore"), "practice": bool(g.get("practice")), "rain": bool(g.get("rain")), } try: resp = requests.post(f"{target_root}/api/games", json=payload, timeout=30) if resp.status_code == 201: inserted += 1 elif resp.status_code == 409: skipped += 1 else: print(f"Error on {g.get('date')} {g.get('time')}: {resp.status_code} {resp.text}", file=sys.stderr) errors += 1 except requests.RequestException as e: print(f"Request error on {g.get('date')} {g.get('time')}: {e}", file=sys.stderr) errors += 1 print(f"Inserted: {inserted}, skipped: {skipped}, errors: {errors}") print(f"Target: {target_root}") if __name__ == "__main__": main()