"""Audit trail — append-only NDJSON log for security-relevant events."""

import json
import logging
import os
from datetime import UTC, datetime
from pathlib import Path

logger = logging.getLogger(__name__)


class AuditLogger:
    """Append-only audit trail for security events."""

    def __init__(self, data_dir: Path) -> None:
        self._log_path = data_dir / "audit.log"
        data_dir.mkdir(parents=True, exist_ok=True)

    def log(self, event: str, **details) -> None:
        """Append an audit event to the log file.

        Events:
          auth_success, auth_failure, data_export, data_purge,
          atom_delete, pii_blocked, token_saved, token_deleted,
          encryption_migration, rate_limited
        """
        entry = {
            "timestamp": datetime.now(UTC).isoformat(),
            "event": event,
            **details,
        }
        try:
            with open(self._log_path, "a") as f:
                f.write(json.dumps(entry, default=str) + "\n")
            # Ensure audit log is owner-readable only
            if self._log_path.exists():
                os.chmod(self._log_path, 0o600)
        except Exception as e:
            logger.warning("Failed to write audit log: %s", e)


# Singleton for easy access
_audit: AuditLogger | None = None


def get_audit_logger(data_dir: Path | None = None) -> AuditLogger:
    """Get or create the audit logger singleton."""
    global _audit
    if _audit is None:
        if data_dir is None:
            data_dir = Path.home() / ".sulci"
        _audit = AuditLogger(data_dir)
    return _audit
