"""Append-only JSONL audit logger for trade actions."""

from __future__ import annotations

import json
import os
from datetime import UTC, datetime
from typing import Any


_dirs_created: set[str] = set()


def log_trade(
    audit_path: str,
    tool: str,
    params: dict[str, Any],
    result: Any = None,
    error: str | None = None,
    dry_run: bool = False,
) -> None:
    """Append a single JSON line to the audit log."""
    entry = {
        "timestamp": datetime.now(UTC).isoformat(),
        "tool": tool,
        "params": params,
        "result": result,
        "error": error,
        "dry_run": dry_run,
    }
    dir_path = os.path.dirname(audit_path)
    if dir_path not in _dirs_created:
        os.makedirs(dir_path, exist_ok=True)
        _dirs_created.add(dir_path)
    with open(audit_path, "a") as f:
        f.write(json.dumps(entry) + "\n")
