import jwt
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from datetime import datetime, timedelta,timezone
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
import os
import base64
from app.core import config

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

SECRET_KEY = "alicorns"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 2880


def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


def create_access_token(*, data: dict, expires_delta: timedelta = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def chacha20Encrypt(plaintext:str, key=config.KINTONE_PSW_CRYPTO_KEY):
    if plaintext is None or plaintext == '':
        return None
    nonce = os.urandom(16)
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None)
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(plaintext.encode('utf-8')) + encryptor.finalize()
    return base64.b64encode(nonce +'𒀸'.encode('utf-8')+ ciphertext).decode('utf-8')

def chacha20Decrypt(encoded_str:str, key=config.KINTONE_PSW_CRYPTO_KEY):
    try:
        decoded_data = base64.b64decode(encoded_str)
        if len(decoded_data) < 18:
            return encoded_str
        special_char = decoded_data[16:20]
        if special_char != '𒀸'.encode('utf-8'):
            return encoded_str
        nonce = decoded_data[:16]
        ciphertext = decoded_data[20:]
    except Exception as e:
        print(f"An error occurred: {e}")
        return encoded_str
    algorithm = algorithms.ChaCha20(key, nonce)
    cipher = Cipher(algorithm, mode=None)
    decryptor = cipher.decryptor()
    plaintext_bytes = decryptor.update(ciphertext) + decryptor.finalize()
    return plaintext_bytes.decode('utf-8')