# -*- coding: utf-8 -*-
"""
修复管理员用户
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from src.core.database import db_manager
from sqlalchemy import text
from werkzeug.security import generate_password_hash

print("Fixing admin user...")

try:
    with db_manager.get_session() as session:
        # Check if admin user exists
        result = session.execute(text("SELECT id FROM users WHERE username = 'admin'"))
        admin_row = result.fetchone()

        password_hash = generate_password_hash('admin123')

        if admin_row:
            print("Admin user exists, updating password...")
            session.execute(text("""
                UPDATE users
                SET password_hash = :password_hash,
                    is_active = 1,
                    updated_at = NOW()
                WHERE username = 'admin'
            """), {'password_hash': password_hash})
            session.commit()
            print("Admin password updated successfully")
        else:
            print("Admin user not found, creating...")
            session.execute(text("""
                INSERT INTO users (
                    username, email, password_hash, role, full_name,
                    is_active, region, created_at, updated_at
                ) VALUES (
                    'admin', 'admin@tsp.com', :password_hash, 'admin', 'Administrator',
                    1, NULL, NOW(), NOW()
                )
            """), {'password_hash': password_hash})
            session.commit()
            print("Admin user created successfully")

        # Verify
        result = session.execute(text("""
            SELECT username, email, role, is_active, full_name
            FROM users
            WHERE username = 'admin'
        """))
        admin_data = result.fetchone()

        if admin_data:
            print("\nVerification:")
            print(f"  Username: {admin_data[0]}")
            print(f"  Email: {admin_data[1]}")
            print(f"  Role: {admin_data[2]}")
            print(f"  Is Active: {admin_data[3]}")
            print(f"  Full Name: {admin_data[4]}")

            # Test password verification
            result = session.execute(text("SELECT password_hash FROM users WHERE username = 'admin'"))
            stored_hash = result.fetchone()[0]
            from werkzeug.security import check_password_hash
            password_ok = check_password_hash(stored_hash, 'admin123')
            print(f"  Password Check: {'PASS' if password_ok else 'FAIL'}")

            if password_ok and admin_data[3]:
                print("\n[SUCCESS] Admin user is ready for login!")
                print("  Username: admin")
                print("  Password: admin123")
            else:
                print("\n[WARNING] User exists but password or status issue")
        else:
            print("\n[ERROR] User not found after creation")

except Exception as e:
    print(f"Error: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

