# backend/app/crypto.py — 커넥터 토큰 대칭 암복호화 (phase-13)
# 평문 토큰은 절대 DB 에 저장하지 않는다. ARI_SECRET_KEY → Fernet 키 파생.
import base64
import hashlib
import json

from cryptography.fernet import Fernet, InvalidToken

from .config import get_settings


def _fernet() -> Fernet:
    # ARI_SECRET_KEY -> sha256(32바이트) -> urlsafe base64 -> Fernet 키
    raw = get_settings().ari_secret_key.encode("utf-8")
    key = base64.urlsafe_b64encode(hashlib.sha256(raw).digest())
    return Fernet(key)


def encrypt_token(token_dict: dict) -> str:
    """{'access_token':..., 'refresh_token':..., 'expires_at':...} -> 암호문 str."""
    return _fernet().encrypt(json.dumps(token_dict).encode("utf-8")).decode("utf-8")


def decrypt_token(enc: str) -> dict:
    if not enc:
        return {}
    try:
        return json.loads(_fernet().decrypt(enc.encode("utf-8")).decode("utf-8"))
    except (InvalidToken, ValueError):
        return {}  # 키 회전/손상 → 빈 dict (호출측은 token_expired 처리)
