#!/usr/bin/env python3
"""Offline pre-release check for an A2A Agent Card.

Asserts three release facts a publisher can get wrong right before serving a
card, each one independently so a failure names its own layer:

1. release version: the card's `version` equals the release being shipped;
2. compatible interface: the first `supportedInterfaces` entry whose
   `protocolBinding` and `protocolVersion` both match the target clients
   (specification section 8.3.1: clients select the first supported entry);
3. endpoint url: when a compatible interface was selected, its `url` must be
   the expected endpoint. With no compatible interface at all, the check
   falls back to a declaration-level match (any entry with the same binding
   declaring the expected URL) and says so; the run still fails overall on
   check 2.

Reads one local JSON file: no network, no accounts, no signature checks.
Structural linting stays with the `agent-card-lint.jq` program published in
the Agent Card implementation guide; this tool only pins release facts.

Exit codes: 0 all checks passed, 1 at least one FAIL line, 2 bad input.
"""
import argparse
import json
import sys


def compatible(entry, binding, protocol):
    """True when the entry speaks the binding and protocol of the target clients."""
    return (isinstance(entry, dict)
            and entry.get("protocolBinding") == binding
            and entry.get("protocolVersion") == protocol)


def main():
    parser = argparse.ArgumentParser(
        description="Offline pre-release check for an A2A Agent Card (local JSON only).")
    parser.add_argument("card", help="path to the Agent Card JSON file")
    parser.add_argument("--binding", default="JSONRPC",
                        help="protocol binding the target clients speak (default: JSONRPC)")
    parser.add_argument("--protocol", default="1.0",
                        help="protocol version the target clients speak (default: 1.0)")
    parser.add_argument("--expect-version", required=True,
                        help="application release the card must declare in its version field")
    parser.add_argument("--expect-url", required=True,
                        help="endpoint URL that must be declared on a binding entry")
    args = parser.parse_args()

    try:
        with open(args.card, "r", encoding="utf-8") as handle:
            card = json.load(handle)
    except OSError as exc:
        print(f"error: cannot read {args.card}: {exc}", file=sys.stderr)
        return 2
    except json.JSONDecodeError as exc:
        print(f"error: {args.card} is not valid JSON: {exc}", file=sys.stderr)
        return 2

    if not isinstance(card, dict):
        print("error: the Agent Card must be a JSON object", file=sys.stderr)
        return 2
    interfaces = card.get("supportedInterfaces")
    if not isinstance(interfaces, list) or not interfaces:
        print("error: supportedInterfaces must be a non-empty array; "
              "run agent-card-lint.jq for the full structural check", file=sys.stderr)
        return 2

    failures = 0

    # 1. Release version.
    version = card.get("version")
    if version == args.expect_version:
        print(f"OK release version: card.version == {args.expect_version}")
    else:
        print(f"FAIL release version: card.version is {version!r}, "
              f"expected {args.expect_version!r}")
        failures += 1

    # 2. First interface compatible with the target clients.
    selected = next((i for i, entry in enumerate(interfaces)
                     if compatible(entry, args.binding, args.protocol)), None)
    if selected is None:
        print(f"FAIL compatible interface: no supportedInterfaces entry has "
              f"protocolBinding={args.binding} and protocolVersion={args.protocol}")
        failures += 1
    else:
        print(f"OK compatible interface: selected supportedInterfaces[{selected}] "
              f"({args.binding} {args.protocol}) url={interfaces[selected].get('url')}")

    # 3. Endpoint url: the entry the selector picked must carry the expected
    #    endpoint, so a URL drift on the compatible interface cannot hide
    #    behind an older entry that still declares the expected URL.
    if selected is not None:
        selected_url = interfaces[selected].get("url")
        if selected_url == args.expect_url:
            print(f"OK endpoint url: selected supportedInterfaces[{selected}] "
                  f"declares {args.expect_url}")
        else:
            print(f"FAIL endpoint url: selected supportedInterfaces[{selected}] "
                  f"declares {selected_url!r}, expected {args.expect_url!r}")
            failures += 1
    else:
        declared = next((i for i, entry in enumerate(interfaces)
                         if isinstance(entry, dict)
                         and entry.get("protocolBinding") == args.binding
                         and entry.get("url") == args.expect_url), None)
        if declared is None:
            print(f"FAIL endpoint url: no {args.binding} entry declares {args.expect_url}")
            failures += 1
        else:
            print(f"OK endpoint url: {args.expect_url} is still declared on "
                  f"supportedInterfaces[{declared}] (declaration only, no "
                  f"compatible interface was selected)")

    if failures:
        print(f"FAIL {args.card}: {failures}/3 checks failed")
        return 1
    print(f"PASS {args.card}: 3/3 checks passed")
    return 0


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