"""Synthetic logging boundary fixture. Python 3.11+, standard library only.
No network requests or file writes. All credentials are disposable canaries.
"""
import copy
import io
import json
import logging
import sys
import unittest

CANARY = "FAKE_TOKEN_7f91"


def record():
    try:
        raise ValueError("upstream rejected " + CANARY)
    except ValueError:
        return logging.LogRecord("adapter", logging.ERROR, __file__, 1,
                                 "tool failed: %s", (CANARY,), sys.exc_info())


class MessageOnly(logging.Formatter):
    def format(self, rec):
        local = copy.copy(rec)
        local.msg = local.getMessage().replace(CANARY, "[REDACTED]")
        local.args = ()
        return super().format(local)


class ExceptionOnly(logging.Formatter):
    def formatException(self, info):
        return "[exception omitted]"


class SafeEvent(logging.Formatter):
    """Dedicated fixed-schema event sink; never serialize the LogRecord."""
    def format(self, rec):
        # IDs are assigned by this demonstration's coordinator, not a caller.
        # Do not generalise this to arbitrary strings from request headers.
        if type(rec.operation_id) is not int or rec.operation_id < 1:
            raise ValueError("invalid operation identity")
        if rec.error_code not in {"TOOL_TIMEOUT", "TOOL_REJECTED"}:
            raise ValueError("unrecognised error code")
        return json.dumps({"event": "tool_failure", "operation_id": rec.operation_id,
                           "error_code": rec.error_code}, sort_keys=True)


def safe_record():
    rec = record()
    rec.operation_id = 42
    rec.error_code = "TOOL_REJECTED"
    return rec


def emit(rec, formatter):
    out = io.StringIO()
    handler = logging.StreamHandler(out)
    handler.setFormatter(formatter)
    handler.handle(rec)
    return out.getvalue()


def demonstration():
    rec = safe_record()
    weak = emit(rec, MessageOnly("%(message)s"))
    logging.Formatter().format(rec)  # First formatter caches the raw exception.
    rec.msg, rec.args = "tool failed", ()
    cached = emit(rec, ExceptionOnly("%(message)s"))
    safe = emit(rec, SafeEvent())
    return {"message_only_leaks": CANARY in weak,
            "exception_override_after_cache_leaks": CANARY in cached,
            "safe_event_leaks": CANARY in safe,
            "safe_event": json.loads(safe)}


class Tests(unittest.TestCase):
    def test_message_redaction_does_not_remove_exception(self):
        text = emit(record(), MessageOnly("%(message)s"))
        self.assertIn("tool failed: [REDACTED]", text)
        self.assertIn("ValueError: upstream rejected " + CANARY, text)

    def test_cached_exception_bypasses_override(self):
        rec = record()
        rec.msg, rec.args = "tool failed", ()
        logging.Formatter().format(rec)
        self.assertIn(CANARY, emit(rec, ExceptionOnly()))
        rec.exc_text = None
        self.assertNotIn(CANARY, emit(rec, ExceptionOnly()))

    def test_allowlist_omits_all_untrusted_fields(self):
        rec = safe_record()
        rec.exc_text = CANARY
        rec.stack_info = CANARY
        rec.request_body = CANARY
        text = emit(rec, SafeEvent())
        self.assertNotIn(CANARY, text)
        self.assertEqual(json.loads(text), {"event": "tool_failure", "operation_id": 42,
                                          "error_code": "TOOL_REJECTED"})

    def test_safe_formatter_does_not_mutate_shared_record(self):
        rec = safe_record()
        before = rec.__dict__.copy()
        emit(rec, SafeEvent())
        self.assertEqual(before, rec.__dict__)

    def test_unsafe_second_handler_still_leaks(self):
        rec = safe_record()
        self.assertNotIn(CANARY, emit(rec, SafeEvent()))
        self.assertIn(CANARY, emit(rec, logging.Formatter()))

    def test_unknown_codes_rejected(self):
        rec = safe_record()
        rec.error_code = CANARY
        with self.assertRaises(ValueError):
            SafeEvent().format(rec)

    def test_non_integer_identity_rejected(self):
        for value in [CANARY, True, 0, -1]:
            with self.subTest(value=value):
                rec = safe_record()
                rec.operation_id = value
                with self.assertRaises(ValueError):
                    SafeEvent().format(rec)


if __name__ == "__main__":
    if "--test" in sys.argv:
        unittest.main(argv=[sys.argv[0]], verbosity=2)
    else:
        print(json.dumps(demonstration(), indent=2))
