"""Tests for console transport behavior."""

from __future__ import annotations

import io
import pathlib
import sys
import unittest


ROOT = pathlib.Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from vedatrace.models import LogLevel, LogRecord
from vedatrace.transports.console import ConsoleTransport


class TestConsoleTransport(unittest.TestCase):
    def test_emit_writes_readable_line(self) -> None:
        stream = io.StringIO()
        transport = ConsoleTransport(stream=stream)
        record = LogRecord.create(
            level=LogLevel.INFO,
            message="hello world",
            service="orders",
            timestamp="2026-02-19T17:42:47.957694Z",
            metadata={"request_id": "abc-123"},
        )

        transport.emit([record])

        output = stream.getvalue().strip()
        self.assertIn("2026-02-19T17:42:47.957694Z", output)
        self.assertIn("[info]", output)
        self.assertIn("orders: hello world", output)
        self.assertIn('{"request_id": "abc-123"}', output)

    def test_emit_does_not_leak_api_key_string(self) -> None:
        fake_api_key = "vt_live_very_secret_key_value"
        stream = io.StringIO()
        transport = ConsoleTransport(stream=stream)
        record = LogRecord.create(
            level=LogLevel.ERROR,
            message="operation failed",
            service="billing",
            timestamp="2026-02-19T17:42:47.957694Z",
            metadata={"request_id": "xyz"},
        )

        transport.emit([record])

        output = stream.getvalue()
        self.assertNotIn(fake_api_key, output)

    def test_emit_respects_enabled_flag(self) -> None:
        stream = io.StringIO()
        transport = ConsoleTransport(stream=stream, enabled=False)
        record = LogRecord.create(
            level=LogLevel.DEBUG,
            message="ignored",
            service="orders",
            timestamp="2026-02-19T17:42:47.957694Z",
            metadata={},
        )

        transport.emit([record])

        self.assertEqual(stream.getvalue(), "")
