"""Simple MCP audit logging."""
from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


def write_audit_event(event: dict[str, Any]) -> None:
    """Append one JSON line to MCP audit log if configured."""
    output_path = os.getenv("AIF_MCP_AUDIT_LOG", "").strip()
    if not output_path:
        return
    try:
        payload = {
            "ts": datetime.now(timezone.utc).isoformat(),
            **event,
        }
        path = Path(output_path)
        path.parent.mkdir(parents=True, exist_ok=True)
        with path.open("a", encoding="utf-8") as f:
            f.write(json.dumps(payload, ensure_ascii=False) + "\n")
    except Exception:
        # Audit failure should not block business flow.
        return

