"""
Run this ONCE after configuring .env and creating the MySQL database in cPanel:

    python init_db.py

It creates all tables and, if no admin user exists yet, prompts you to create one.
Safe to re-run — it won't duplicate tables or users.
"""
import getpass
from werkzeug.security import generate_password_hash
from app import create_app
from extensions import db
from models import AdminUser

app = create_app()

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

    if AdminUser.query.count() == 0:
        print("\nNo admin user found — let's create one.")
        username = input("Admin username [admin]: ").strip() or "admin"
        password = getpass.getpass("Admin password: ")
        confirm = getpass.getpass("Confirm password: ")
        if password != confirm:
            print("Passwords did not match. Run this script again.")
        else:
            user = AdminUser(username=username, password_hash=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            print(f"Admin user '{username}' created. You can now log in.")
    else:
        print("Admin user already exists — skipping.")
