import re
from passlib.context import CryptContext
from fastapi import Request
from sqlalchemy.orm import Session
from src.utils.logger import log_error
from src.utils.exceptions import PasswordValidationException

# Setup the passlib context for password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def validate_password_strength(password: str, db: Session, request: Request):
    """
    Validates the strength of a password.
    The password must be at least 8 characters long, contain at least one uppercase letter,
    one lowercase letter, one digit, and one special character.
    Logs errors if the password is weak.
    """
    error_message = None

    if len(password) < 8:
        error_message = "Password must be at least 8 characters long."
    elif not re.search(r"[A-Z]", password):
        error_message = "Password must contain at least one uppercase letter."
    elif not re.search(r"[a-z]", password):
        error_message = "Password must contain at least one lowercase letter."
    elif not re.search(r"\d", password):
        error_message = "Password must contain at least one digit."
    elif not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
        error_message = "Password must contain at least one special character."

    if error_message:
        # Log the error to the database
        log_error(db, error_message, path=str(request.url), method=request.method)

        # Raise the custom exception with the desired response structure
        raise PasswordValidationException(message=error_message)

def get_password_hash(password: str, db: Session, request: Request) -> str:
    """
    Validate and hash the given password using bcrypt.
    :param password: The plain text password.
    :return: The hashed password.
    """
    # Validate the password strength before hashing
    validate_password_strength(password, db, request)

    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    Verify the given password against the hashed password.
    :param plain_password: The plain text password.
    :param hashed_password: The hashed password stored in the database.
    :return: True if the password matches, False otherwise.
    """
    return pwd_context.verify(plain_password, hashed_password)
