from datetime import datetime, timedelta
from jose import jwt, JWTError
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from cryptography.fernet import Fernet
from src.db.session import get_db
from src.db.models.user import User
from src.core.config import settings

# Initialize password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# Generate or load a secret key for symmetric encryption
encryption_key = Fernet.generate_key()
cipher_suite = Fernet(encryption_key)

def create_access_token(data: dict) -> str:
    """
    Create a JWT token and then encrypt it using Fernet symmetric encryption.
    """
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
    to_encode.update({"exp": expire})

    # Create the JWT token
    encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)

    # Encrypt the JWT token
    encrypted_token = cipher_suite.encrypt(encoded_jwt.encode('utf-8'))

    return encrypted_token.decode('utf-8')

def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)) -> User:
    """
    Decrypt the encrypted token and then validate it using JWT.
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        # Decrypt the token first
        decrypted_token = cipher_suite.decrypt(token.encode('utf-8')).decode('utf-8')

        # Decode the JWT token
        payload = jwt.decode(decrypted_token, settings.secret_key, algorithms=[settings.algorithm])
        user_id: str = payload.get("sub")
        if user_id is None:
            raise credentials_exception
    except (JWTError, Exception) as e:
        raise credentials_exception from e

    # Fetch the user from the database
    user = db.query(User).filter(User.id == user_id).first()
    if user is None:
        raise credentials_exception

    return user

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    Verifies that a plain text password matches the hashed password.
    """
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -> str:
    """
    Hashes a plain text password using bcrypt.
    """
    return pwd_context.hash(password)
