import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path

import jwt

from backend.core.config import get_app_settings
from backend.core import root_logger
from backend.core.security.hasher import get_hasher

ALGORITHM = "HS256"

logger = root_logger.get_logger("security")
settings = get_app_settings()

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
  settings = get_app_settings()

  to_encode = data.copy()
  expires_delta = expires_delta or timedelta(minutes=settings.EXP_TOKEN)

  expire = datetime.now(timezone.utc) + expires_delta

  to_encode["exp"] = expire
  return jwt.encode(to_encode, settings.SECRET, algorithm=ALGORITHM)

def create_refresh_token(data: dict) -> str:
  return create_access_token(data, expires_delta=timedelta(days=settings.EXP_REFRESH))

def create_file_token(file_path: Path) -> str:
  token_data = {"file": str(file_path)}
  return create_access_token(token_data, expires_delta=timedelta(minutes=30))


def hash_password(password: str) -> str:
  """Takes in a raw password and hashes it. Used prior to saving a new password to the database."""
  return get_hasher().hash(password)


def url_safe_token() -> str:
  """Generates a cryptographic token without embedded data. Used for password reset tokens and invitation tokens"""
  return secrets.token_urlsafe(24)

def verify_token(exp: int):
  expried = datetime.fromtimestamp(exp / 1e3)
  return expried < datetime.now(timezone.utc)
