"""Audit logging helpers for tenant and security events."""

from __future__ import annotations

from pathlib import Path

from platform.logging.platform_logger import get_platform_logger, log_structured


class AuditLogger:
    """Write audit events to platform and tenant log targets."""

    def __init__(self) -> None:
        self.logger = get_platform_logger("audit")

    def log(self, *, tenant_id: str | None, actor: str | None, action: str, status: str = "success", **fields) -> None:
        log_structured(
            self.logger,
            "audit_event",
            tenant_id=tenant_id,
            actor=actor,
            action=action,
            status=status,
            **fields,
        )
        if tenant_id:
            tenant_dir = Path("/var/www/html/flask_server/logs/tenants") / tenant_id
            tenant_dir.mkdir(parents=True, exist_ok=True)
            with (tenant_dir / "audit.log").open("a", encoding="utf-8") as handle:
                handle.write(f"{action}|{status}|actor={actor or 'unknown'}\n")

