"""Offline MCP 2026-07-28 preflight: resource discovery, issuer and header checks.

Python 3.11+ standard library. NOT an OAuth client or MCP server.
No network calls, token processing, or secrets.
"""
from __future__ import annotations

import base64
from urllib.parse import urlsplit

PROTOCOL = "2026-07-28"


def valid_resource_uri(uri: str) -> bool:
    p = urlsplit(uri)
    return p.scheme == "https" and bool(p.hostname) and not p.fragment and not p.username and not p.password


def validate_protected_resource(metadata: dict, expected_resource: str) -> list[str]:
    """Reject unexpected resource identity and non-HTTPS authorization servers."""
    if not valid_resource_uri(expected_resource) or metadata.get("resource") != expected_resource:
        raise ValueError("protected resource mismatch")
    issuers = metadata.get("authorization_servers")
    if not isinstance(issuers, list) or not issuers or not all(
        isinstance(item, str) and valid_resource_uri(item) for item in issuers
    ):
        raise ValueError("missing or invalid authorization servers")
    return issuers


def validate_callback_issuer(expected_issuer: str, actual_issuer: str | None,
                             advertised_iss_support: bool) -> None:
    """RFC 9207 check; caller must separately validate state, PKCE and redirect URI."""
    if actual_issuer is None:
        if advertised_iss_support:
            raise ValueError("issuer missing although advertised")
        return
    if actual_issuer != expected_issuer:
        raise ValueError("issuer mismatch")


def encode_header_value(value: str) -> str:
    """2026-07-28 sentinel for unsafe/non-ASCII MCP header values."""
    safe = value and all(32 <= ord(c) <= 126 for c in value)
    if safe and value == value.strip() and not (value.startswith("=?base64?") and value.endswith("?=")):
        return value
    return "=?base64?" + base64.b64encode(value.encode("utf-8")).decode("ascii") + "?="


def decode_header_value(value: str) -> str:
    if value.startswith("=?base64?") and value.endswith("?="):
        return base64.b64decode(value[9:-2], validate=True).decode("utf-8")
    return value


def build_tool_call(name: str, args: dict, request_id: int = 1) -> tuple[dict, dict]:
    """Build a 2026-era request envelope and matching routing headers."""
    body = {"jsonrpc": "2.0", "id": request_id, "method": "tools/call", "params": {
        "name": name, "arguments": args,
        "_meta": {"io.modelcontextprotocol/protocolVersion": PROTOCOL,
                  "io.modelcontextprotocol/clientInfo": {"name": "scorebook-preflight", "version": "1.0"},
                  "io.modelcontextprotocol/clientCapabilities": {}}}}
    headers = {"Content-Type": "application/json",
               "Accept": "application/json, text/event-stream",
               "MCP-Protocol-Version": PROTOCOL,
               "Mcp-Method": "tools/call", "Mcp-Name": encode_header_value(name)}
    return body, headers


def verify_routing_headers(body: dict, headers: dict) -> None:
    """Minimal mirror check; full SDK additionally validates custom Mcp-Param-* headers."""
    params = body.get("params", {})
    meta = params.get("_meta", {})
    if (headers.get("MCP-Protocol-Version") != PROTOCOL or
            meta.get("io.modelcontextprotocol/protocolVersion") != PROTOCOL or
            headers.get("Mcp-Method") != body.get("method") or
            decode_header_value(headers.get("Mcp-Name", "")) != params.get("name")):
        raise ValueError("MCP request headers disagree with JSON-RPC body")
