"""Tests for structured JSONL logging."""

import json
import logging
import os
import tempfile
from pathlib import Path

from cloudsense_dx_mcp.logging_config import (
    JsonFormatter,
    SESSION_ID,
    get_system_info,
    log_event,
)


class TestJsonFormatter:
    def test_formats_as_json_line(self):
        formatter = JsonFormatter()
        record = logging.LogRecord(
            name="test", level=logging.INFO,
            pathname="", lineno=0, msg="hello", args=(), exc_info=None,
        )
        output = formatter.format(record)
        parsed = json.loads(output)
        assert parsed["level"] == "INFO"
        assert parsed["message"] == "hello"
        assert "ts" in parsed
        assert "thread" in parsed

    def test_uses_json_fields_when_present(self):
        formatter = JsonFormatter()
        record = logging.LogRecord(
            name="test", level=logging.DEBUG,
            pathname="", lineno=0, msg="", args=(), exc_info=None,
        )
        record.json_fields = {"tool": "fetch", "duration_s": 1.5}
        output = formatter.format(record)
        parsed = json.loads(output)
        assert parsed["tool"] == "fetch"
        assert parsed["duration_s"] == 1.5
        assert "message" not in parsed


class TestLogEvent:
    def test_emits_structured_entry(self):
        test_logger = logging.getLogger("test_log_event")
        test_logger.setLevel(logging.DEBUG)

        with tempfile.NamedTemporaryFile(mode="w", suffix=".jsonl", delete=False) as f:
            tmppath = f.name

        try:
            handler = logging.FileHandler(tmppath, encoding="utf-8")
            handler.setFormatter(JsonFormatter())
            test_logger.addHandler(handler)

            log_event(test_logger, "INFO", tool="test_tool", duration_s=2.0)
            handler.flush()

            content = Path(tmppath).read_text(encoding="utf-8").strip()
            parsed = json.loads(content)
            assert parsed["tool"] == "test_tool"
            assert parsed["duration_s"] == 2.0
            assert parsed["level"] == "INFO"
        finally:
            test_logger.removeHandler(handler)
            os.unlink(tmppath)


class TestSessionId:
    def test_is_8_char_hex(self):
        assert len(SESSION_ID) == 8
        int(SESSION_ID, 16)  # should not raise


class TestSystemInfo:
    def test_contains_required_fields(self):
        info = get_system_info()
        assert "os" in info
        assert "python" in info
        assert "machine" in info
