"""Offline tests: python -m unittest discover -s examples -p 'test_mcp_2026_preflight.py'."""
import unittest
from mcp_2026_preflight import (
    validate_protected_resource, validate_callback_issuer,
    build_tool_call, verify_routing_headers, encode_header_value, decode_header_value,
)


class PreflightTests(unittest.TestCase):
    def test_metadata_good(self):
        self.assertEqual(validate_protected_resource({
            "resource": "https://mcp.example.com/mcp",
            "authorization_servers": ["https://auth.example.com/tenant"]
        }, "https://mcp.example.com/mcp"), ["https://auth.example.com/tenant"])

    def test_metadata_rejects_wrong_resource(self):
        with self.assertRaises(ValueError):
            validate_protected_resource({"resource": "https://evil.example/mcp",
                                         "authorization_servers": ["https://auth.example.com"]},
                                        "https://mcp.example.com/mcp")

    def test_metadata_rejects_http_issuer(self):
        with self.assertRaises(ValueError):
            validate_protected_resource({"resource": "https://mcp.example.com/mcp",
                                         "authorization_servers": ["http://auth.example.com"]},
                                        "https://mcp.example.com/mcp")

    def test_callback_issuer(self):
        validate_callback_issuer("https://auth.example.com", "https://auth.example.com", True)
        with self.assertRaises(ValueError):
            validate_callback_issuer("https://auth.example.com", "https://evil.example.com", True)
        with self.assertRaises(ValueError):
            validate_callback_issuer("https://auth.example.com", None, True)
        validate_callback_issuer("https://auth.example.com", None, False)

    def test_header_roundtrip(self):
        for name in ["get_weather", "你好", " padded ", "=?base64?literal?="]:
            with self.subTest(name=name):
                self.assertEqual(decode_header_value(encode_header_value(name)), name)
                body, headers = build_tool_call(name, {"city": "Pune"})
                verify_routing_headers(body, headers)

    def test_mismatch_rejected(self):
        body, headers = build_tool_call("search", {"query": "mcp"})
        headers["Mcp-Method"] = "tools/list"
        with self.assertRaises(ValueError):
            verify_routing_headers(body, headers)


if __name__ == "__main__":
    unittest.main()
