"""
Python 108 — Admin Setup Script
Run once: python setup_admin.py
"""
import sys, os
sys.path.insert(0, os.path.dirname(__file__))

from werkzeug.security import generate_password_hash
import database as db

def main():
    db.init_db()
    print("\n" + "="*45)
    print("  Python 108 — Create Admin Account")
    print("="*45)

    username = input("Admin username (default: admin): ").strip() or "admin"
    email    = input("Admin email: ").strip()
    while True:
        password = input("Admin password (min 6 chars): ").strip()
        if len(password) >= 6:
            break
        print("  Password must be at least 6 characters.")

    existing = db.get_user_by_username(username)
    if existing:
        print(f"\n  User '{username}' already exists.")
        overwrite = input("  Overwrite? (yes/no): ").strip().lower()
        if overwrite != "yes":
            print("  Aborted.")
            return

    pw_hash = generate_password_hash(password)
    ok = db.create_user(username, email, pw_hash, role="admin")

    if not ok:
        # Update existing user to admin
        conn = db.get_db()
        conn.execute(
            "UPDATE users SET password_hash=?, role='admin', is_active=1 WHERE username=?",
            (pw_hash, username)
        )
        conn.commit()
        conn.close()

    print(f"\n  ✓ Admin account '{username}' ready.")
    print("  Start the app:  python app.py")
    print("  Login at:       http://localhost:5000/login\n")

if __name__ == "__main__":
    main()
