"""
seed.py — Populate all leaderboard tables from the SimpleBoards API.

Fetches all entries from the remote leaderboard and distributes them:
  global  — all entries
  weekly  — entries created within the past 7 days
  daily   — entries created within the past 24 hours

WARNING: This drops and recreates all tables — do not run against a production database.

Usage:
    py scripts/seed.py

Output database: instance/leaderboard.db (Flask's default instance folder)
"""

import sys
import os
import json
from datetime import datetime, timezone, timedelta
from urllib.request import Request, urlopen

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from models import db, GlobalEntry, WeeklyEntry, DailyEntry

API_URL = "https://api.simpleboards.dev/api/leaderboards/dd93a42a-14cd-4c3a-1560-08dec1ce0164/entries"
API_KEY = "c3da28fe-c423-49ae-9377-336147c3e1c3"


def fetch_entries():
    """Fetch all entries from the SimpleBoards API and return them as a list of dicts."""
    req = Request(API_URL, headers={"X-API-Key": API_KEY})
    with urlopen(req) as resp:
        data = json.loads(resp.read())
    return data


def parse_entry(raw):
    """Convert a raw API entry dict into (name, score, created) fields."""
    name = raw["playerDisplayName"]
    score = int(raw["score"])
    # Parse the ISO timestamp and make it timezone-aware
    created = datetime.fromisoformat(raw["createdAt"].replace("Z", "+00:00"))
    return name, score, created


def build_model_entries(model, raw_entries, since=None):
    """
    Build a list of model instances from raw API entries.
    If since is provided, only entries created after that datetime are included.
    """
    entries = []
    for raw in raw_entries:
        name, score, created = parse_entry(raw)
        if since and created < since:
            continue
        entries.append(model(name=name, score=score, created=created))
    return entries


def main():
    print("Fetching entries from SimpleBoards API...")
    raw_entries = fetch_entries()
    print(f"Fetched {len(raw_entries)} entries.")

    now = datetime.now(timezone.utc)
    one_week_ago  = now - timedelta(days=7)
    one_day_ago   = now - timedelta(days=1)

    app = create_app()
    with app.app_context():
        print("Dropping and recreating all tables...")
        db.drop_all()
        db.create_all()

        global_entries = build_model_entries(GlobalEntry, raw_entries)
        weekly_entries = build_model_entries(WeeklyEntry, raw_entries, since=one_week_ago)
        daily_entries  = build_model_entries(DailyEntry,  raw_entries, since=one_day_ago)

        db.session.add_all(global_entries + weekly_entries + daily_entries)
        db.session.commit()

        print(f"Seeded {len(global_entries)} rows into 'global'.")
        print(f"Seeded {len(weekly_entries)} rows into 'weekly'.")
        print(f"Seeded {len(daily_entries)} rows into 'daily'.")
        print("Done. Database written to instance/leaderboard.db.")


if __name__ == "__main__":
    main()
