#!/usr/bin/env python3
"""CC0. Check 1–10 draft citations in one HTTP or MCP tool call. Python 3 stdlib only.
No model API, credentials, installation, or automatic retries.
"""
import argparse
import json
import sys
import urllib.error
import urllib.parse
import urllib.request

EXAMPLE = {"citations": [
    {"id": "present", "url": "https://bozos.si/tools/quote-checker.md", "quote": "establishes textual presence only"},
    {"id": "absent", "url": "https://bozos.si/tools/quote-checker.md", "quote": "A unicorn wrote this quotation."},
    {"id": "unavailable", "url": "https://bozos.si/examples/no-such-source", "quote": "Evidence must be readable."},
]}

def request_json(base, path, payload, protocol=None):
    headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
               "User-Agent": "BOZOS-Citation-Example/1.0"}
    if protocol:
        headers["MCP-Protocol-Version"] = protocol
    body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
    if len(body) > 65536:
        raise ValueError("The complete request must fit within 64 KiB.")
    request = urllib.request.Request(base + path, data=body, headers=headers)
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        delay = error.headers.get("Retry-After")
        raise RuntimeError(f"HTTP {error.code}; Retry-After={delay!r}. No automatic retry.") from None

def check_citations(payload, base="https://bozos.si", transport="http"):
    if transport == "http":
        return request_json(base, "/api/v1/citation-check", payload)
    initialized = request_json(base, "/api/mcp", {
        "jsonrpc": "2.0", "id": 1, "method": "initialize",
        "params": {"protocolVersion": "2025-11-25", "capabilities": {},
                   "clientInfo": {"name": "bozos-citation-example", "version": "1.0"}},
    })
    if "error" in initialized:
        raise RuntimeError("MCP initialization failed: " + json.dumps(initialized["error"]))
    protocol = initialized["result"]["protocolVersion"]
    # BOZOS is stateless; its initialized notification needs no client session.
    notification = urllib.request.Request(base + "/api/mcp", data=json.dumps({
        "jsonrpc": "2.0", "method": "notifications/initialized"
    }).encode(), headers={"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "MCP-Protocol-Version": protocol})
    with urllib.request.urlopen(notification, timeout=15) as response:
        response.read()
    reply = request_json(base, "/api/mcp", {
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": {"name": "checkCitations", "arguments": payload},
    }, protocol)
    if "error" in reply:
        raise RuntimeError("MCP protocol error: " + json.dumps(reply["error"]))
    result = reply["result"]
    if result.get("isError"):
        raise RuntimeError("MCP tool error: " + json.dumps(result.get("content", [])))
    return result["structuredContent"]

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", nargs="?", help="JSON file containing citations, or - for stdin; defaults to the public demo")
    parser.add_argument("--transport", choices=["http", "mcp"], default="http")
    parser.add_argument("--base-url", default="https://bozos.si")
    args = parser.parse_args()
    parsed = urllib.parse.urlsplit(args.base_url)
    if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost")):
        parser.error("Use HTTPS, or HTTP on localhost for development.")
    if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/"):
        parser.error("--base-url must be an origin, without credentials, path, query, or fragment.")
    try:
        payload = EXAMPLE
        if args.input == "-":
            payload = json.load(sys.stdin)
        elif args.input:
            with open(args.input, encoding="utf-8") as file:
                payload = json.load(file)
        result = check_citations(payload, args.base_url.rstrip("/"), args.transport)
        # Keep the full evidence, including failures, hashes, passages and incompleteness.
        print(json.dumps(result, indent=2, ensure_ascii=False))
        print("A match proves textual presence only, not truth or support for a claim.", file=sys.stderr)
        return 0
    except (ValueError, OSError, KeyError, RuntimeError) as error:
        print(f"Citation check failed: {error}", file=sys.stderr)
        return 1

if __name__ == "__main__":
    sys.exit(main())
