"""
初始化管理員帳號腳本
"""
from sqlalchemy.orm import Session
from app.models import engine, Base
from app.models.user import User, UserRole
from app.utils.security import get_password_hash
import os

def create_admin_user(db: Session):
    """建立預設管理員帳號"""
    admin_email = os.getenv("ADMIN_EMAIL", "admin@example.com")
    admin_password = os.getenv("ADMIN_PASSWORD", "admin123")

    # 檢查是否已存在
    existing = db.query(User).filter(User.email == admin_email).first()
    if existing:
        print(f"Admin user already exists: {admin_email}")
        return existing

    # 建立管理員
    admin = User(
        email=admin_email,
        password_hash=get_password_hash(admin_password),
        display_name="Administrator",
        language="zh-TW",
        role=UserRole.admin
    )
    db.add(admin)
    db.commit()
    db.refresh(admin)

    print(f"Admin user created: {admin_email}")
    return admin

def init_database():
    """初始化資料庫並建立預設帳號"""
    from sqlalchemy.orm import sessionmaker

    # 建立所有資料表
    Base.metadata.create_all(bind=engine)
    print("Database tables created.")

    # 建立 session
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    db = SessionLocal()

    try:
        create_admin_user(db)
    finally:
        db.close()

if __name__ == "__main__":
    init_database()
