"""Audit logging for the PXE webapp.

Every write-action route should call ``audit(action, detail)`` to record
who did what. The log lives at ``AUDIT_LOG`` (configurable via env var)
and is consumed by the /audit page.
"""

import logging

from flask import request

import config

_audit_handler = logging.FileHandler(config.AUDIT_LOG, mode="a")
_audit_handler.setFormatter(logging.Formatter("%(asctime)s  %(message)s"))

audit_logger = logging.getLogger("pxe_audit")
audit_logger.setLevel(logging.INFO)
if not audit_logger.handlers:
    audit_logger.addHandler(_audit_handler)


def audit(action, detail=""):
    """Write an entry to the audit log."""
    ip = request.remote_addr if request else "system"
    audit_logger.info(f"[{ip}] {action}: {detail}")
