import secrets
import string
from sqlalchemy.orm import Session
from database import ApiKey, User
from typing import List, Optional

def generate_api_key(length: int = 32) -> str:
    """Generate a secure random API key"""
    alphabet = string.ascii_letters + string.digits
    api_key = ''.join(secrets.choice(alphabet) for _ in range(length))
    return f"smtp_{api_key}"

def create_api_key(db: Session, user_id: int, key_name: str) -> ApiKey:
    """Create a new API key for a user"""
    # Generate unique API key
    while True:
        api_key = generate_api_key()
        existing = db.query(ApiKey).filter(ApiKey.api_key == api_key).first()
        if not existing:
            break
    
    db_api_key = ApiKey(
        user_id=user_id,
        key_name=key_name,
        api_key=api_key,
        is_active=True,
        usage_count=0
    )
    db.add(db_api_key)
    db.commit()
    db.refresh(db_api_key)
    return db_api_key

def get_user_api_keys(db: Session, user_id: int) -> List[ApiKey]:
    """Get all API keys for a user"""
    return db.query(ApiKey).filter(ApiKey.user_id == user_id).all()

def get_api_key_by_id(db: Session, key_id: int, user_id: int) -> Optional[ApiKey]:
    """Get a specific API key by ID and user"""
    return db.query(ApiKey).filter(
        ApiKey.id == key_id,
        ApiKey.user_id == user_id
    ).first()

def revoke_api_key(db: Session, key_id: int, user_id: int) -> bool:
    """Revoke (deactivate) an API key"""
    api_key = get_api_key_by_id(db, key_id, user_id)
    if not api_key:
        return False
    
    api_key.is_active = False
    db.commit()
    return True

def delete_api_key(db: Session, key_id: int, user_id: int) -> bool:
    """Permanently delete an API key"""
    api_key = get_api_key_by_id(db, key_id, user_id)
    if not api_key:
        return False
    
    db.delete(api_key)
    db.commit()
    return True

def reactivate_api_key(db: Session, key_id: int, user_id: int) -> bool:
    """Reactivate a revoked API key"""
    api_key = get_api_key_by_id(db, key_id, user_id)
    if not api_key:
        return False
    
    api_key.is_active = True
    db.commit()
    return True

def validate_api_key(db: Session, api_key: str) -> Optional[ApiKey]:
    """Validate an API key and return the key record"""
    return db.query(ApiKey).filter(
        ApiKey.api_key == api_key,
        ApiKey.is_active == True
    ).first()

def get_api_key_stats(db: Session, user_id: int) -> dict:
    """Get API key statistics for a user"""
    total_keys = db.query(ApiKey).filter(ApiKey.user_id == user_id).count()
    active_keys = db.query(ApiKey).filter(
        ApiKey.user_id == user_id,
        ApiKey.is_active == True
    ).count()
    total_usage = db.query(ApiKey).filter(ApiKey.user_id == user_id).with_entities(
        db.func.sum(ApiKey.usage_count)
    ).scalar() or 0
    
    return {
        "total_keys": total_keys,
        "active_keys": active_keys,
        "inactive_keys": total_keys - active_keys,
        "total_usage": total_usage
    }
