#!/usr/bin/env python3
"""
SEC Stats Upload Watcher — Setup Script
Run this once to configure and install the watcher service.
"""

import os
import sys
import subprocess
import shutil
import json
from pathlib import Path

SEC_STATS = Path("~/Documents/sec_stats").expanduser()
PLIST_SRC = SEC_STATS / "com.sec.stats.upload-watcher.plist"
PLIST_DST = Path("~/Library/LaunchAgents/com.sec.stats.upload-watcher.plist").expanduser()

def run(cmd, **kwargs):
    return subprocess.run(cmd, shell=True, check=False, **kwargs)

def header(title):
    print(f"\n{'─'*52}")
    print(f"  {title}")
    print(f"{'─'*52}")

print("\n" + "═"*52)
print("  SEC Stats Upload Watcher — Setup")
print("═"*52)

# ── Step 1: Install Python dependencies ────────────────────────
header("Step 1: Installing Python dependencies")
run(f"{sys.executable} -m pip install gspread google-auth --break-system-packages -q")
print("  ✓ gspread and google-auth installed")

# ── Step 2: Check watch folder exists ──────────────────────────
header("Step 2: Verifying watch folder")
watch = Path(
    "~/Library/CloudStorage/GoogleDrive-tbrasher@sec.org"
    "/My Drive/SEC Baseball – Game File Upload (File responses)"
    "/Upload XML File (File responses)"
).expanduser()

if watch.exists():
    print(f"  ✓ Watch folder found:\n    {watch}")
else:
    print(f"  ⚠ Watch folder NOT found:\n    {watch}")
    print("    Make sure Google Drive for Desktop is running and synced.")
    print("    Update WATCH_FOLDER in watch_uploads.py if the path differs.")

# ── Step 3: Google Sheets API setup ────────────────────────────
header("Step 3: Google Sheets API — Service Account Setup")
creds_path = SEC_STATS / "service_account.json"

if creds_path.exists():
    print(f"  ✓ Service account key already exists at:\n    {creds_path}")
else:
    print("""
  To read the Game Registry sheet automatically, you need a
  Google service account key. Here's how to create one:

  1. Go to: https://console.cloud.google.com/
  2. Create a new project (or use an existing one)
  3. Enable the Google Sheets API:
       APIs & Services → Enable APIs → search "Google Sheets API"
  4. Create a service account:
       APIs & Services → Credentials → Create Credentials
       → Service Account → give it a name → Done
  5. Create a JSON key:
       Click the service account → Keys → Add Key → JSON
       → Download the file
  6. Rename the downloaded file to: service_account.json
  7. Copy it to: ~/Documents/sec_stats/service_account.json
  8. Share your Game Registry Google Sheet with the service
     account email address (shown in the JSON as "client_email")
     → Give it "Viewer" access

  Then re-run this setup script.

  ALTERNATIVE: If you skip this step, the watcher will still
  work but you'll need to manually pass --game-id when ingesting
  files (see watch_uploads.py --help).
""")

# ── Step 4: Prompt for Sheet ID ────────────────────────────────
header("Step 4: Configure Sheet ID")
watcher_path = SEC_STATS / "watch_uploads.py"
with open(watcher_path) as f:
    content = f.read()

if "YOUR_SHEET_ID_HERE" in content:
    print("""
  Your Game Registry Sheet ID is the long string in its URL:
  https://docs.google.com/spreadsheets/d/SHEET_ID_HERE/edit

  Copy just the ID portion (between /d/ and /edit).
""")
    sheet_id = input("  Paste your Baseball Game Registry Sheet ID: ").strip()
    if sheet_id and sheet_id != "YOUR_SHEET_ID_HERE":
        content = content.replace("YOUR_SHEET_ID_HERE", sheet_id)
        with open(watcher_path, "w") as f:
            f.write(content)
        print(f"  ✓ Sheet ID saved to watch_uploads.py")
    else:
        print("  Skipped — edit SHEET_ID in watch_uploads.py manually.")
else:
    print("  ✓ Sheet ID already configured")

# ── Step 5: Install launchd service ────────────────────────────
header("Step 5: Installing background service (launchd)")

if not PLIST_SRC.exists():
    print(f"  ✗ Plist not found at {PLIST_SRC}")
else:
    # Unload existing if present
    run(f"launchctl unload {PLIST_DST} 2>/dev/null")

    shutil.copy(PLIST_SRC, PLIST_DST)
    result = run(f"launchctl load {PLIST_DST}")

    if result.returncode == 0:
        print(f"  ✓ Service installed and started")
        print(f"    Polls every 30 seconds for new XML uploads")
        print(f"    Logs to: {SEC_STATS}/watch_uploads.log")
    else:
        print(f"  ✗ Failed to load service")
        print(f"    Try manually: launchctl load {PLIST_DST}")

# ── Summary ─────────────────────────────────────────────────────
print(f"""
{'═'*52}
  Setup complete!

  The watcher is now running in the background.
  Every 30 seconds it checks:
    {watch}

  When a new XML appears, it:
    1. Looks up the Game ID from the Registry sheet
    2. Copies the file to data/raw/baseball/2026/TEAM/
    3. Runs parse_games.py --game-id ...
    4. Runs export_json.py to refresh the stats

  Useful commands:
    # Check if service is running
    launchctl list | grep sec.stats

    # View live logs
    tail -f ~/Documents/sec_stats/watch_uploads.log

    # Stop the service
    launchctl unload ~/Library/LaunchAgents/com.sec.stats.upload-watcher.plist

    # Restart the service
    launchctl unload ~/Library/LaunchAgents/com.sec.stats.upload-watcher.plist
    launchctl load ~/Library/LaunchAgents/com.sec.stats.upload-watcher.plist

    # Run a manual one-time scan
    python3 ~/Documents/sec_stats/watch_uploads.py
{'═'*52}
""")
