"""
AI Model logging configuration.

Controls whether AI model requests/responses are logged to disk.
Easy to extend with additional log targets, formats, or filters.
"""

import os
import json
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding

from app.config import settings
#16字节密钥
ENCRYPTION_KEY = b'videogen@202605!'



def encrypt_data(data: dict) -> str:
    data_str = json.dumps(data, ensure_ascii=False, sort_keys=True)
    data_bytes = data_str.encode("utf-8")
    
    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(data_bytes) + padder.finalize()
    
    iv = os.urandom(16)
    cipher = Cipher(algorithms.AES(ENCRYPTION_KEY), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
    
    return base64.b64encode(iv + encrypted_data).decode("utf-8")


def decrypt_data(encrypted_str: str) -> dict:
    try:
        encrypted_bytes = base64.b64decode(encrypted_str)
        iv = encrypted_bytes[:16]
        ciphertext = encrypted_bytes[16:]
        
        cipher = Cipher(algorithms.AES(ENCRYPTION_KEY), modes.CBC(iv), backend=default_backend())
        decryptor = cipher.decryptor()
        padded_data = decryptor.update(ciphertext) + decryptor.finalize()
        
        unpadder = padding.PKCS7(128).unpadder()
        data_bytes = unpadder.update(padded_data) + unpadder.finalize()
        
        return json.loads(data_bytes.decode("utf-8"))
    except Exception:
        return {}


# ── Feature toggle ──────────────────────────────────────────
AI_LOG_ENABLED: bool = True  # Set True to enable logging, or use env var AI_LOG_ENABLED=true


# ── Log output settings ────────────────────────────────────
LOG_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    "log", "AiModel",
)
# 请求响应日志目录
LOG_R_Q_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    "log", "RequestResponse",
)

LOG_FILENAME_FORMAT = "{date}.log"  # e.g. 2026-05-12.log
LOG_DATE_FORMAT = "%Y-%m-%d"


# ── Fields to include in each log entry ────────────────────
LOG_FIELDS = [
    "timestamp",
    "model_name",
    "model_id",
    "provider",
    "api_base",
    "request",
    "response",
    "error",
]


def is_enabled() -> bool:
    """Check if AI model logging is enabled."""
    env_val = os.environ.get("AI_LOG_ENABLED", "").lower()
    if env_val in ("true", "1", "yes"):
        return True
    if env_val in ("false", "0", "no"):
        return False
    return AI_LOG_ENABLED
