from fastapi import HTTPException, Request, Depends
from sqlalchemy.orm import Session
from sqlalchemy import text
from datetime import datetime
import logging

from app.db.database import get_db

logger = logging.getLogger(__name__)


async def validate_api_key(request: Request, db: Session = Depends(get_db)):
    """Validate API key from X-API-Key header against system_api_key table"""
    api_key = request.headers.get("X-API-Key")
    
    if not api_key:
        logger.warning("API request without API key")
        raise HTTPException(
            status_code=401,
            detail="API key required",
            headers={"WWW-Authenticate": "ApiKey"}
        )
    
    # Query the system API key
    cursor = db.execute(
        text("SELECT api_key FROM system_api_key WHERE id = 1")
    )
    result = cursor.fetchone()
    
    if not result or result[0] != api_key:
        logger.warning(f"Invalid API key attempt: {api_key[:8]}...")
        raise HTTPException(
            status_code=401,
            detail="Invalid API key"
        )
    
    # Update usage statistics
    db.execute(text("""
        UPDATE system_api_key 
        SET last_used_at = CURRENT_TIMESTAMP,
            usage_count = usage_count + 1
        WHERE id = 1
    """))
    db.commit()
    
    return api_key