# Ajout à web_sentinel_api.py - Endpoints pour validation de licence

@app.route('/api/v1/license/verify', methods=['POST'])
def verify_license():
    """Vérifier une licence via la base de données PostgreSQL."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "JSON body required"}), 400
        
        email = data.get('email', '').lower().strip()
        tier = data.get('tier', '').lower()
        
        if not email or not tier:
            return jsonify({"error": "email and tier required"}), 400
        
        # Vérification en base PostgreSQL
        try:
            import psycopg2
            db_url = os.getenv('DATABASE_URL', 'postgresql://websentinel_user:WebSentinel2025SecureDB!@web-sentinel-db:5432/websentinel_prod')
            
            with psycopg2.connect(db_url) as conn:
                with conn.cursor() as cursor:
                    cursor.execute("""
                        SELECT tier, created_at, last_used, is_active, daily_limit, monthly_limit
                        FROM api_key 
                        WHERE email = %s AND is_active = TRUE
                    """, (email,))
                    
                    row = cursor.fetchone()
                    
            if not row:
                return jsonify({
                    "valid": False,
                    "reason": f"No active subscription found for {email}"
                }), 404
            
            db_tier, created_at, last_used, is_active, daily_limit, monthly_limit = row
            
            # Vérifier la cohérence du tier
            if db_tier and db_tier.lower() != tier:
                return jsonify({
                    "valid": False,
                    "reason": f"Tier mismatch: requested={tier}, database={db_tier}"
                }), 400
            
            # Mettre à jour last_used
            try:
                with psycopg2.connect(db_url) as conn:
                    with conn.cursor() as cursor:
                        cursor.execute("""
                            UPDATE api_key 
                            SET last_used = NOW()
                            WHERE email = %s
                        """, (email,))
                        conn.commit()
            except:
                pass  # Non critique
            
            return jsonify({
                "valid": True,
                "tier": db_tier,
                "limits": {
                    "daily": daily_limit,
                    "monthly": monthly_limit
                },
                "metadata": {
                    "created_at": created_at.isoformat() if created_at else None,
                    "last_used": datetime.utcnow().isoformat() + "Z"
                }
            })
                        
        except ImportError:
            return jsonify({"error": "PostgreSQL driver not available"}), 500
        except Exception as db_error:
            return jsonify({"error": f"Database error: {str(db_error)}"}), 500
            
    except Exception as e:
        return jsonify({"error": f"License verification failed: {str(e)}"}), 500


@app.route('/api/v1/license/users', methods=['POST']) 
def create_license_user():
    """Créer un utilisateur avec licence dans la base PostgreSQL."""
    try:
        data = request.get_json()
        if not data:
            return jsonify({"error": "JSON body required"}), 400
            
        # Vérification de l'authentification admin
        api_key = data.get('api_key')
        if api_key != 'ws_admin_master_key_2025':  # Clé admin temporaire
            return jsonify({"error": "Admin API key required"}), 401
        
        name = data.get('name', '').strip()
        email = data.get('email', '').lower().strip()
        tier = data.get('tier', 'free').lower()
        
        if not name or not email:
            return jsonify({"error": "name and email required"}), 400
        
        # Générer une clé API pour l'utilisateur
        import hashlib
        import uuid
        
        # Clé API lisible
        api_key_raw = f"ws_{tier}_{uuid.uuid4().hex[:8]}"
        api_key_hash = hashlib.sha256(api_key_raw.encode()).hexdigest()
        
        # Limites selon le tier
        limits_map = {
            'free': {'daily': 10, 'monthly': 100},
            'pro': {'daily': 500, 'monthly': 5000}, 
            'enterprise': {'daily': 2000, 'monthly': 20000},
            'sysop': {'daily': 10000, 'monthly': 100000}
        }
        limits = limits_map.get(tier, limits_map['free'])
        
        try:
            import psycopg2
            db_url = os.getenv('DATABASE_URL', 'postgresql://websentinel_user:WebSentinel2025SecureDB!@web-sentinel-db:5432/websentinel_prod')
            
            with psycopg2.connect(db_url) as conn:
                with conn.cursor() as cursor:
                    # Vérifier si l'utilisateur existe
                    cursor.execute("SELECT id FROM api_key WHERE email = %s", (email,))
                    if cursor.fetchone():
                        return jsonify({"error": f"User {email} already exists"}), 400
                    
                    # Créer l'utilisateur
                    cursor.execute("""
                        INSERT INTO api_key (key_hash, name, email, tier, created_at, last_used, is_active, daily_limit, monthly_limit)
                        VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE, %s, %s)
                        RETURNING id
                    """, (api_key_hash, name, email, tier, limits['daily'], limits['monthly']))
                    
                    user_id = cursor.fetchone()[0]
                    conn.commit()
            
            return jsonify({
                "success": True,
                "user": {
                    "id": user_id,
                    "name": name,
                    "email": email,
                    "tier": tier,
                    "api_key": api_key_raw,  # Retourner la clé en clair une seule fois
                    "limits": limits
                },
                "message": f"User {name} created successfully with {tier} license"
            })
                        
        except ImportError:
            return jsonify({"error": "PostgreSQL driver not available"}), 500
        except Exception as db_error:
            return jsonify({"error": f"Database error: {str(db_error)}"}), 500
            
    except Exception as e:
        return jsonify({"error": f"User creation failed: {str(e)}"}), 500