"""
seed_data.py
------------
Run this ONCE when setting up a fresh club (fresh database file) to:
  1. Create all the database tables from models.py
  2. Insert the 5 fixed competition templates
  3. Create one demo admin account so you have a way to log in

Usage:
    python seed_data.py

Safe to re-run: it checks what already exists before inserting anything,
so running it twice won't create duplicates.
"""

from werkzeug.security import generate_password_hash

from app import create_app
from app.extensions import db
from app.models import CompetitionTemplate, User

app = create_app()

# The 5 competition types you specified. format_type controls whether the
# signup form asks for a partner; gender_category is used to describe/filter
# the competition (not yet enforced at signup - that's a "nicety" for later).
TEMPLATES = [
    {"name": "Matchplay Singles - Men", "format_type": "singles", "gender_category": "men"},
    {"name": "Matchplay Singles - Ladies", "format_type": "singles", "gender_category": "ladies"},
    {"name": "Matchplay Doubles - Men", "format_type": "doubles", "gender_category": "men"},
    {"name": "Matchplay Doubles - Ladies", "format_type": "doubles", "gender_category": "ladies"},
    {"name": "Matchplay Doubles - Mixed", "format_type": "doubles", "gender_category": "mixed"},
]

with app.app_context():
    db.create_all()
    print("Database tables created (or already existed).")

    for t in TEMPLATES:
        exists = CompetitionTemplate.query.filter_by(name=t["name"]).first()
        if not exists:
            db.session.add(CompetitionTemplate(**t))
            print(f"  Added template: {t['name']}")
    db.session.commit()

    admin_email = "admin@example.com"
    if not User.query.filter_by(email=admin_email).first():
        admin = User(
            name="Club Admin",
            email=admin_email,
            password_hash=generate_password_hash("admin123"),
            role="admin",
        )
        db.session.add(admin)
        db.session.commit()
        print(f"\nDemo admin created:\n  email: {admin_email}\n  password: admin123")
        print("  (change this password before deploying for real)")

    print("\nSeed complete. Run the app with: flask --app run.py run --debug")
