"""JSONL audit logger for scandar-guard. Never logs raw message content."""
from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from typing import Optional

from .findings import RuntimeFinding


class AuditLogger:
    def __init__(self, log_file: Optional[str] = "./scandar-guard-audit.jsonl") -> None:
        self.log_file = log_file
        self._enabled = log_file is not None

    def log_event(
        self,
        event_type: str,
        session_id: str,
        findings: list[RuntimeFinding],
        metadata: Optional[dict] = None,
    ) -> None:
        if not self._enabled:
            return
        entry = {
            "ts": datetime.now(timezone.utc).isoformat(),
            "session_id": session_id,
            "event": event_type,
            "findings_count": len(findings),
            "findings": [f.to_dict() for f in findings],
            "metadata": metadata or {},
            # NOTE: raw message content is never included here
        }
        self._write_line(entry)

    def log_session_end(self, session_id: str, stats: dict) -> None:
        if not self._enabled:
            return
        entry = {
            "ts": datetime.now(timezone.utc).isoformat(),
            "session_id": session_id,
            "event": "session_end",
            "stats": stats,
        }
        self._write_line(entry)

    def _write_line(self, entry: dict) -> None:
        if not self.log_file:
            return
        try:
            with open(self.log_file, "a", encoding="utf-8") as f:
                f.write(json.dumps(entry) + "\n")
        except OSError:
            # Never crash the user's agent due to a logging error
            pass
