"""
Admin 계정 설정 스크립트
- 기존 admin 계정이 있으면 is_admin = True로 업데이트
- 없으면 새로 생성

사용법:
  python setup_admin.py                    # 현재 admin 계정 상태 확인
  python setup_admin.py --create           # admin 계정 생성/업데이트
  python setup_admin.py --email new@email.com --password newpass  # 커스텀 계정 생성
"""
import sqlite3
import os
import sys
import bcrypt

# 설정
DEFAULT_ADMIN_EMAIL = "admin@example.com"
DEFAULT_ADMIN_PASSWORD = "admin123"
DEFAULT_ADMIN_NAME = "Administrator"

db_path = os.path.join(os.path.dirname(__file__), 'autonet.db')


def get_password_hash(password: str) -> str:
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')


def check_admin_status():
    """현재 admin 계정 상태 확인"""
    if not os.path.exists(db_path):
        print(f"Database not found: {db_path}")
        return None

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # 모든 사용자의 admin 상태 확인
    print("\n=== All Users ===")
    cursor.execute("SELECT id, email, name, is_admin, is_dealer FROM users ORDER BY id")
    users = cursor.fetchall()

    if not users:
        print("No users found in database.")
    else:
        for user in users:
            admin_status = "ADMIN" if user[3] else "user"
            dealer_status = "(dealer)" if user[4] else ""
            print(f"  ID:{user[0]} | {user[1]} | {user[2] or 'N/A'} | {admin_status} {dealer_status}")

    # admin 계정만 필터링
    print("\n=== Admin Accounts ===")
    cursor.execute("SELECT id, email, name FROM users WHERE is_admin = 1")
    admins = cursor.fetchall()

    if not admins:
        print("No admin accounts found!")
        print(f"Run 'python setup_admin.py --create' to create admin account.")
    else:
        for admin in admins:
            print(f"  ID:{admin[0]} | {admin[1]} | {admin[2] or 'N/A'}")

    conn.close()
    return admins


def create_or_update_admin(email=None, password=None, name=None):
    """Admin 계정 생성 또는 업데이트"""
    email = email or DEFAULT_ADMIN_EMAIL
    password = password or DEFAULT_ADMIN_PASSWORD
    name = name or DEFAULT_ADMIN_NAME

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # 기존 계정 확인
    cursor.execute("SELECT id, email, is_admin FROM users WHERE email = ?", (email,))
    existing = cursor.fetchone()

    if existing:
        user_id, user_email, is_admin = existing
        if is_admin:
            print(f"Admin account already exists: {user_email} (ID: {user_id})")
        else:
            # is_admin = True로 업데이트
            cursor.execute("UPDATE users SET is_admin = 1 WHERE id = ?", (user_id,))
            conn.commit()
            print(f"Updated user to admin: {user_email} (ID: {user_id})")
    else:
        # 새 계정 생성
        import hashlib
        import uuid

        # referral_code 생성
        referral_code = hashlib.sha256(uuid.uuid4().hex.encode()).hexdigest()[:8].upper()

        password_hash = get_password_hash(password)

        cursor.execute("""
            INSERT INTO users (email, password_hash, name, is_admin, is_active, cc_balance, referral_code, country)
            VALUES (?, ?, ?, 1, 1, 100, ?, 'Korea')
        """, (email, password_hash, name, referral_code))

        conn.commit()
        user_id = cursor.lastrowid
        print(f"Created new admin account: {email} (ID: {user_id})")
        print(f"  Password: {password}")

    conn.close()


def main():
    print(f"Database: {db_path}")
    print(f"Exists: {os.path.exists(db_path)}")

    if len(sys.argv) == 1:
        # 상태 확인만
        check_admin_status()
    elif "--create" in sys.argv:
        # admin 계정 생성/업데이트
        email = None
        password = None
        name = None

        for i, arg in enumerate(sys.argv):
            if arg == "--email" and i + 1 < len(sys.argv):
                email = sys.argv[i + 1]
            elif arg == "--password" and i + 1 < len(sys.argv):
                password = sys.argv[i + 1]
            elif arg == "--name" and i + 1 < len(sys.argv):
                name = sys.argv[i + 1]

        create_or_update_admin(email, password, name)
        print("\n--- After Update ---")
        check_admin_status()
    else:
        print(__doc__)


if __name__ == "__main__":
    main()
