#!/usr/bin/env python3
"""
QUICK FIX - Verifica e corregge problema login
==============================================

Questo script:
1. Verifica che l'utente demo esista nel DB
2. Verifica/ripara password hash
3. Testa che Flask risponda
4. Mostra URL esatti per il login
"""

import pymysql
import bcrypt
import os

# Configurazione
DB_CONFIG = {
    'host': 'localhost',
    'user': 'enigma_user',
    'password': 'arcana2026',
    'database': 'enigma',
    'charset': 'utf8mb4'
}

DEMO_USER = {
    'email': 'demo@studium.it',
    'password': 'demo123',
    'tenant_code': 'DEMO'
}

def fix_demo_user():
    """Fix password utente demo"""
    print("=" * 70)
    print("ENIGMA - FIX UTENTE DEMO")
    print("=" * 70)
    
    try:
        # Connessione DB
        print("\n[1] Connessione database...")
        conn = pymysql.connect(**DB_CONFIG)
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        print("✓ Connesso")
        
        # Trova tenant
        print(f"\n[2] Cerco tenant {DEMO_USER['tenant_code']}...")
        cursor.execute(
            "SELECT id, codice FROM tenants WHERE codice = %s",
            (DEMO_USER['tenant_code'],)
        )
        tenant = cursor.fetchone()
        
        if not tenant:
            print(f"✗ Tenant {DEMO_USER['tenant_code']} non trovato!")
            print("\nCrea tenant con:")
            print(f"INSERT INTO tenants (codice, nome, email_admin, stato) VALUES")
            print(f"  ('{DEMO_USER['tenant_code']}', 'Demo Tenant', 'admin@demo.it', 'attivo');")
            return False
        
        print(f"✓ Tenant trovato: ID {tenant['id']}")
        tenant_id = tenant['id']
        
        # Cerca utente
        print(f"\n[3] Cerco utente {DEMO_USER['email']}...")
        cursor.execute(
            "SELECT * FROM tenant_users WHERE email = %s AND id_tenant = %s",
            (DEMO_USER['email'], tenant_id)
        )
        user = cursor.fetchone()
        
        # Genera nuovo hash
        new_hash = bcrypt.hashpw(
            DEMO_USER['password'].encode('utf-8'),
            bcrypt.gensalt()
        ).decode('utf-8')
        
        if user:
            print(f"✓ Utente trovato: ID {user['id']}")
            
            # Aggiorna password
            print(f"\n[4] Aggiorno password...")
            cursor.execute(
                """UPDATE tenant_users 
                   SET password_hash = %s
                   WHERE id = %s""",
                (new_hash, user['id'])
            )
            conn.commit()
            print("✓ Password aggiornata")
            
        else:
            print("✗ Utente non trovato, lo creo...")
            
            # Crea utente
            cursor.execute(
                """INSERT INTO tenant_users 
                   (id_tenant, email, password_hash, nome, ruolo)
                   VALUES (%s, %s, %s, %s, %s)""",
                (tenant_id, DEMO_USER['email'], new_hash, 'Demo User', 'admin')
            )
            conn.commit()
            print("✓ Utente creato")
        
        # Verifica finale
        print(f"\n[5] Verifica finale...")
        cursor.execute(
            "SELECT * FROM tenant_users WHERE email = %s AND id_tenant = %s",
            (DEMO_USER['email'], tenant_id)
        )
        user = cursor.fetchone()
        
        # Test password
        is_valid = bcrypt.checkpw(
            DEMO_USER['password'].encode('utf-8'),
            user['password_hash'].encode('utf-8')
        )
        
        if is_valid:
            print("✓ Password verificata correttamente!")
        else:
            print("✗ Errore: password non valida!")
            return False
        
        conn.close()
        
        # Mostra credenziali
        print("\n" + "=" * 70)
        print("✓ UTENTE DEMO PRONTO")
        print("=" * 70)
        print(f"\nCredenziali login:")
        print(f"  Email: {DEMO_USER['email']}")
        print(f"  Password: {DEMO_USER['password']}")
        print(f"  Tenant: {DEMO_USER['tenant_code']}")
        print(f"\nURL login:")
        print(f"  http://localhost:5000/login")
        print(f"\nAPI login:")
        print(f"  POST http://localhost:5000/auth/login")
        print(f"\nTest con curl:")
        print(f"""  curl -X POST http://localhost:5000/auth/login \\
    -H "Content-Type: application/json" \\
    -d '{{"email": "{DEMO_USER['email']}", "password": "{DEMO_USER['password']}", "tenant_code": "{DEMO_USER['tenant_code']}"}}'""")
        
        print("\n" + "=" * 70)
        
        return True
        
    except Exception as e:
        print(f"\n✗ ERRORE: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    fix_demo_user()
