#!/usr/bin/env python3
"""
Quick Login Test - Verifica rapida problema login demo
"""

import pymysql
import bcrypt
import requests
import json

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

BASE_URL = 'http://localhost:5000'
DEMO_USER = {
    'email': 'demo@studium.it',
    'password': 'demo123',
    'tenant_code': 'DEMO'
}

print("=" * 70)
print("QUICK LOGIN TEST")
print("=" * 70)

# TEST 1: Verifica utente nel DB
print("\n[1] Verifico utente nel database...")
try:
    conn = pymysql.connect(**DB_CONFIG)
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    cursor.execute("""
        SELECT tu.*, t.codice as tenant_code
        FROM tenant_users tu
        JOIN tenants t ON tu.id_tenant = t.id
        WHERE tu.email = %s AND t.codice = %s
    """, (DEMO_USER['email'], DEMO_USER['tenant_code']))
    
    user = cursor.fetchone()
    
    if user:
        print(f"✓ Utente trovato: ID {user['id']}")
        print(f"  Email: {user['email']}")
        print(f"  Tenant: {user['tenant_code']}")
        print(f"  Password hash presente: {bool(user['password_hash'])}")
        
        # Verifica password
        if user['password_hash']:
            try:
                is_valid = bcrypt.checkpw(
                    DEMO_USER['password'].encode('utf-8'),
                    user['password_hash'].encode('utf-8')
                )
                if is_valid:
                    print(f"✓ Password hash VALIDO")
                else:
                    print(f"✗ Password hash NON VALIDO - serve reset!")
            except Exception as e:
                print(f"✗ Errore verifica password: {e}")
        else:
            print(f"✗ Password hash MANCANTE!")
    else:
        print(f"✗ Utente NON trovato nel database!")
    
    conn.close()
    
except Exception as e:
    print(f"✗ Errore database: {e}")
    exit(1)

# TEST 2: Verifica endpoint Flask
print("\n[2] Verifico endpoint Flask...")
try:
    # Test homepage
    response = requests.get(f"{BASE_URL}/", timeout=5)
    print(f"✓ Homepage: Status {response.status_code}")
    
    # Test login page
    response = requests.get(f"{BASE_URL}/auth/login", timeout=5)
    print(f"✓ Login page: Status {response.status_code}")
    
except requests.exceptions.ConnectionError:
    print(f"✗ Flask NON in esecuzione su {BASE_URL}")
    print(f"  Avvia con: python3 app.py")
    exit(1)
except Exception as e:
    print(f"✗ Errore endpoint: {e}")

# TEST 3: Test login API
print("\n[3] Test login API...")
try:
    login_data = {
        'email': DEMO_USER['email'],
        'password': DEMO_USER['password'],
        'tenant_code': DEMO_USER['tenant_code']
    }
    
    response = requests.post(
        f"{BASE_URL}/auth/login",
        json=login_data,
        timeout=10
    )
    
    print(f"Status Code: {response.status_code}")
    print(f"Response: {response.text[:500]}")
    
    if response.status_code == 200:
        data = response.json()
        if 'access_token' in data:
            print(f"✓ LOGIN RIUSCITO!")
            print(f"  Token ricevuto: {data['access_token'][:30]}...")
        else:
            print(f"✗ Login OK ma token mancante")
            print(f"  Response: {json.dumps(data, indent=2)}")
    else:
        print(f"✗ LOGIN FALLITO")
        try:
            error = response.json()
            print(f"  Errore: {error}")
        except:
            print(f"  Response: {response.text}")
    
except Exception as e:
    print(f"✗ Errore login: {e}")

print("\n" + "=" * 70)
print("Fine test")
print("=" * 70)
