"""Tests for audit module."""

from __future__ import annotations

import json
import os
import tempfile

from liquid_mcp.audit import log_trade


class TestLogTrade:
    def test_creates_file_and_writes_entry(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            path = os.path.join(tmpdir, "subdir", "trades.jsonl")
            log_trade(
                audit_path=path,
                tool="place_order",
                params={"symbol": "BTC-PERP", "size": 100},
                result={"order_id": "ord_1"},
            )
            assert os.path.exists(path)
            with open(path) as f:
                line = f.readline()
            entry = json.loads(line)
            assert entry["tool"] == "place_order"
            assert entry["params"]["symbol"] == "BTC-PERP"
            assert entry["result"]["order_id"] == "ord_1"
            assert entry["error"] is None
            assert entry["dry_run"] is False
            assert "timestamp" in entry

    def test_appends_multiple_entries(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            path = os.path.join(tmpdir, "trades.jsonl")
            log_trade(path, "place_order", {"size": 100})
            log_trade(path, "cancel_order", {"order_id": "x"})
            with open(path) as f:
                lines = f.readlines()
            assert len(lines) == 2
            assert json.loads(lines[0])["tool"] == "place_order"
            assert json.loads(lines[1])["tool"] == "cancel_order"

    def test_dry_run_flag(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            path = os.path.join(tmpdir, "trades.jsonl")
            log_trade(path, "place_order", {}, dry_run=True)
            with open(path) as f:
                entry = json.loads(f.readline())
            assert entry["dry_run"] is True

    def test_error_field(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            path = os.path.join(tmpdir, "trades.jsonl")
            log_trade(path, "place_order", {}, error="max order exceeded")
            with open(path) as f:
                entry = json.loads(f.readline())
            assert entry["error"] == "max order exceeded"
