"""
Audit logging for security-relevant events.

Provides structured JSON audit logs for scan operations, data deletions,
and other security-sensitive actions.
"""
import json
import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

audit_logger = logging.getLogger("audit")


def configure_audit_logging():
    """Configure audit logger with file handler. Call once at app startup."""
    if audit_logger.handlers:
        return  # Already configured

    # In frozen PyInstaller builds, write to %APPDATA%\CerebionRivet\ (writable)
    # In development, write to data/ directory next to the database
    if getattr(sys, "frozen", False):
        appdata = os.environ.get("APPDATA") or os.environ.get("HOME", str(Path.home()))
        data_dir = Path(appdata) / "CerebionRivet"
    else:
        data_dir = Path(__file__).parent.parent / "data"
    data_dir.mkdir(parents=True, exist_ok=True)

    handler = logging.FileHandler(data_dir / "audit.log")
    handler.setFormatter(logging.Formatter("%(message)s"))
    audit_logger.addHandler(handler)
    audit_logger.setLevel(logging.INFO)


def log_audit_event(action: str, user_id: str = "local", details: dict = None):
    """Log a security-relevant event for audit purposes."""
    event = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "action": action,
        "user_id": user_id,
        "details": details or {},
    }
    audit_logger.info(json.dumps(event))
