#!/usr/bin/env python3
"""Seed demo point-events so the weekly / monthly / global leaderboard tabs
are populated out of the box.

  python scripts/seed_points.py            → seed if no SEED rows yet
  python scripts/seed_points.py --purge    → remove all SEED rows

Real matches keep working normally: when an admin distributes a prize,
award_match_points() writes real ledger rows on top of these.
"""
import sys, os, random
from datetime import datetime, timedelta

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from app import create_app
from app.extensions import db
from app.models.user import User
from app.models.game import Game
from app.models.leaderboard import PointEvent
from app.services.leaderboard_service import POINTS_WIN, POINTS_PARTICIPATION

SEED_PREFIX = "SEED:"
SEASON_NAMES = [
    "Weekly Cup", "Night Series", "Open Qualifier", "Community Clash",
    "Rookie Rumble", "Pro Am Showdown", "Weekend Warriors", "Masters Qualifier",
]


def purge():
    n = PointEvent.query.filter(PointEvent.reason.like(f"{SEED_PREFIX}%")).delete(synchronize_session=False)
    db.session.commit()
    print(f"purged {n} seed rows")


def seed():
    if PointEvent.query.filter(PointEvent.reason.like(f"{SEED_PREFIX}%")).count():
        print("seed rows already exist — nothing to do (use --purge first to reseed)")
        return
    users = [u for u in User.query.order_by(User.id).all()]
    games = Game.query.filter_by(is_active=True).all()
    if not users or not games:
        print("no users/games to seed")
        return

    rng = random.Random(20260921)  # deterministic
    now = datetime.utcnow()
    # Per-user "skill" so ranking looks stable and interesting
    skill = {u.id: rng.uniform(0.35, 1.0) for u in users}
    skill[1] = 0.85  # admin stays near the top → YOU badge visible

    buckets = [("week", 1, 6, 5), ("month", 8, 29, 9), ("older", 31, 45, 6)]
    created = 0
    for bucket, dmin, dmax, per_game in buckets:
        for g in games:
            n_events = per_game
            for _ in range(n_events):
                u = rng.choice(users)
                won = rng.random() < skill[u.id] * 0.75
                days_ago = rng.randint(dmin, dmax)
                hours_ago = rng.randint(0, 23)
                created_at = now - timedelta(days=days_ago, hours=hours_ago)
                season = rng.choice(SEASON_NAMES)
                if won:
                    pts, kind = POINTS_WIN, "win"
                    prize = round(rng.uniform(3, 45), 2)
                else:
                    pts, kind = POINTS_PARTICIPATION, "participation"
                    prize = 0.0
                db.session.add(PointEvent(
                    user_id=u.id, game_id=g.id, match_id=None, kind=kind,
                    points=pts, prize=prize,
                    reason=f"{SEED_PREFIX}{season} — {g.name}",
                    created_at=created_at,
                ))
                created += 1
    db.session.commit()
    print(f"seeded {created} point events across {len(users)} users / {len(games)} games")

    # quick window summary for game 1
    from app.services.leaderboard_service import window_rows
    g1 = games[0]
    for d in (None, 7, 30):
        rows = window_rows(g1.id, days=d)
        top = ", ".join(f"{r.user.display_name}:{r.points}" for r in rows[:5])
        print(f"  window days={d}: {len(rows)} players | top: {top}")


if __name__ == "__main__":
    app = create_app()
    with app.app_context():
        if "--purge" in sys.argv:
            purge()
        else:
            seed()
