#!/usr/bin/env python3
"""Initialize database tables and create admin user."""

import hashlib
import bcrypt
from app.database import engine, SessionLocal
from app.models import Base, AdminUser

def normalize_password(password: str) -> str:
    """Normalize password to handle bcrypt's 72-byte limitation."""
    password_bytes = password.encode('utf-8')
    if len(password_bytes) > 72:
        return hashlib.sha256(password_bytes).hexdigest()
    return password

# Create all tables
print("Creating database tables...")
Base.metadata.create_all(bind=engine)
print("✅ Tables created successfully!")

# Create admin user
session = SessionLocal()
try:
    # Delete existing user if present (to recreate with new hash)
    existing = session.query(AdminUser).filter(AdminUser.email == "bruno@taaazzz-prog.fr").first()
    if existing:
        print("ℹ️  Deleting existing admin user to recreate with new hash...")
        session.delete(existing)
        session.commit()
    
    password = "@51008473@ZoE@"
    normalized = normalize_password(password)
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(normalized.encode('utf-8'), salt).decode('utf-8')
    
    admin = AdminUser(
        email="bruno@taaazzz-prog.fr",
        hashed_password=hashed_password,
        role="sysop"
    )
    session.add(admin)
    session.commit()
    print("✅ Admin user created successfully!")
    print(f"   Email: bruno@taaazzz-prog.fr")
    print(f"   Role: sysop")
    print(f"   Password normalized: {len(normalized)} chars")
except Exception as e:
    session.rollback()
    print(f"❌ Error: {e}")
    raise
finally:
    session.close()
