"""Capped mesh audit log."""
from __future__ import annotations

import json
import logging
import os
import time
from typing import Any

_log = logging.getLogger(__name__)

from persistence import MUGI_DIR, secure_atomic_write


MESH_DIR = os.path.join(MUGI_DIR, "mesh")
AUDIT_PATH = os.path.join(MESH_DIR, "audit.jsonl")
MAX_LINES = 10_000
KEEP_LINES = 8_000


def _read_lines() -> list[str]:
    if not os.path.isfile(AUDIT_PATH):
        return []
    try:
        with open(AUDIT_PATH, "r", encoding="utf-8") as f:
            return [line for line in f if line.strip()]
    except Exception:
        _log.debug("mesh audit read failed", exc_info=True)
        return []


def _write_lines(lines: list[str]) -> None:
    secure_atomic_write(AUDIT_PATH, "".join(lines))


def append_audit(entry: dict[str, Any]) -> None:
    os.makedirs(MESH_DIR, exist_ok=True)
    payload = dict(entry)
    payload.setdefault("ts", time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()))
    line = json.dumps(payload, separators=(",", ":"), ensure_ascii=False) + "\n"
    lines = _read_lines()
    lines.append(line)
    if len(lines) > MAX_LINES:
        lines = lines[-KEEP_LINES:]
    _write_lines(lines)


def read_audit(limit: int = 100, offset: int = 0) -> list[dict[str, Any]]:
    lines = _read_lines()
    total = len(lines)
    start = max(0, total - max(1, int(limit)) - max(0, int(offset)))
    end = max(0, total - max(0, int(offset)))
    rows = lines[start:end]
    out: list[dict[str, Any]] = []
    for row in rows:
        try:
            obj = json.loads(row)
            if isinstance(obj, dict):
                out.append(obj)
        except Exception:
            _log.debug("mesh audit skipped malformed line", exc_info=True)
            continue
    return out


def clear_audit() -> int:
    lines = _read_lines()
    count = len(lines)
    if count > 0:
        _write_lines([])
    return count
