"""LockedIn Labs: optional A2A SDK exercise over real loopback HTTP.

Python 3.11+ (verified with 3.12). Prepare a NEW virtual environment:
  python3 -m venv .venv-a2a
  .venv-a2a/bin/python -m pip install --upgrade "pip==26.2.0"
  .venv-a2a/bin/python -m pip install 'a2a-sdk[http-server]==1.2.3' \
    'httpx==0.28.1' 'starlette==1.10.0' 'uvicorn==0.38.0' 'protobuf==7.36.2'
  .venv-a2a/bin/python -m pip check
  .venv-a2a/bin/python fde-a2a-sdk-lab.py compare

Windows: use .venv-a2a\\Scripts\\python.exe in place of .venv-a2a/bin/python.
Installation needs registry access; the program never installs or downloads.
`python3 fde-a2a-sdk-lab.py check` checks only the local acceptance function,
without third-party packages, a socket, or protocol execution.

SDK 1.2.3 implements A2A 1.0; this is not the older v0.3 Python API.
The SDK owns Agent Card discovery, JSON-RPC framing, dispatch and task storage.
Our executor and client acceptance rule are scripted over fictional P-17.
Each case uses a fresh memory-only store and ephemeral 127.0.0.1 listener.
No model, authentication, cloud access, persistence or production guarantee.
References checked 2026-10-25:
https://pypi.org/project/a2a-sdk/1.2.3/
https://a2a-protocol.org/latest/tutorials/python/5-start-server/
https://a2aproject.github.io/a2a-python/docs/migrations/v1_0/
"""
import argparse
import asyncio
from contextlib import AsyncExitStack, suppress
from importlib.metadata import PackageNotFoundError, version
import json
import socket
import sys


SOURCE = {"sourceId": "P-17", "dueDate": "2026-11-12"}
PINNED_PACKAGES = {"a2a-sdk": "1.2.3", "httpx": "0.28.1", "starlette": "1.10.0",
                   "uvicorn": "0.38.0", "protobuf": "7.36.2"}
SCENARIOS = ("clarify", "held-artifact")


def validate_artifact(task, expected):
    """A tiny receiving-client fixture rule, separate from protocol completion."""
    if (task["id"], task["contextId"]) != (expected["id"], expected["contextId"]):
        return "hold: wrong task or context"
    if task["state"] != "TASK_STATE_COMPLETED":
        return "hold: task unfinished"
    artifacts = task["artifacts"]
    if len(artifacts) != 1 or len(artifacts[0].get("parts", [])) != 1:
        return "hold: expected one structured artifact"
    if artifacts[0]["parts"][0].get("data") != SOURCE:
        return "hold: artifact does not match the supplied source"
    return "accept: matches this fixture"


def check():
    """Dependency-free controls do not stand in for running the SDK cases."""
    task = {"id": "synthetic-task", "contextId": "synthetic-context",
            "state": "TASK_STATE_COMPLETED", "artifacts": [{"parts": [{"data": dict(SOURCE)}]}]}
    controls = [
        ("matching-fixture", task, task, "accept: matches this fixture"),
        ("wrong-task", {**task, "id": "another-task"}, task, "hold: wrong task or context"),
        ("wrong-context", {**task, "contextId": "another-context"}, task, "hold: wrong task or context"),
        ("unfinished", {**task, "state": "TASK_STATE_INPUT_REQUIRED"}, task, "hold: task unfinished"),
        ("missing-artifact", {**task, "artifacts": []}, task, "hold: expected one structured artifact"),
        ("wrong-source", {**task, "artifacts": [{"parts": [{"data": {**SOURCE, "sourceId": "P-99"}}]}]}, task,
         "hold: artifact does not match the supplied source"),
        ("wrong-date", {**task, "artifacts": [{"parts": [{"data": {**SOURCE, "dueDate": "2026-11-13"}}]}]}, task,
         "hold: artifact does not match the supplied source"),
    ]
    results = []
    for name, candidate, expected, decision in controls:
        actual = validate_artifact(candidate, expected)
        if actual != decision:
            raise AssertionError(f"Acceptance control failed: {name}")
        results.append({"control": name, "decision": actual})
    return {"mode": "dependency-free fixture checks; no SDK or HTTP execution", "checks": results}


def require_packages():
    installed = {}
    for package, required in PINNED_PACKAGES.items():
        try:
            installed[package] = version(package)
        except PackageNotFoundError:
            raise RuntimeError(f"Missing {package}. Follow this file's virtual-environment installation instructions.") from None
        if installed[package] != required:
            raise RuntimeError(f"Expected {package}=={required}; found {installed[package]}. Use the documented isolated environment.")
    return installed


async def run_case(scenario):
    installed = require_packages()
    # Optional imports stay out of the dependency-free check and --help paths.
    import httpx
    import uvicorn
    from a2a.client import A2ACardResolver, ClientConfig, ClientFactory
    from a2a.helpers import new_task, new_text_message
    from a2a.server.agent_execution import AgentExecutor
    from a2a.server.request_handlers import DefaultRequestHandler
    from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
    from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
    from a2a.types import (AgentCapabilities, AgentCard, AgentInterface, AgentSkill,
                           GetTaskRequest, Part, Role, SendMessageRequest, TaskState)
    from google.protobuf.json_format import MessageToDict, ParseDict
    from google.protobuf.struct_pb2 import Value
    from starlette.applications import Starlette

    class ReviewDateExecutor(AgentExecutor):
        async def execute(self, context, event_queue):
            if context.current_task is None:
                await event_queue.enqueue_event(new_task(
                    context.task_id, context.context_id, TaskState.TASK_STATE_SUBMITTED,
                    history=[context.message]))
            updater = TaskUpdater(event_queue, context.task_id, context.context_id)
            if context.get_user_input() != "Use procedure P-17.":
                await updater.requires_input(new_text_message(
                    "Which procedure should I read?", task_id=context.task_id,
                    context_id=context.context_id))
                return
            await updater.start_work()
            # Read the synthetic fixture, with an intentionally mismatched
            # source label in the independent held-artifact control.
            artifact = {**SOURCE, "sourceId": "P-99" if scenario == "held-artifact" else SOURCE["sourceId"]}
            await updater.add_artifact([Part(data=ParseDict(artifact, Value()))], name="Review due date")
            await updater.complete()

        async def cancel(self, context, event_queue):
            await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()

    def snapshot(task):
        return {"id": task.id, "contextId": task.context_id,
                "state": TaskState.Name(task.status.state),
                "artifacts": [MessageToDict(artifact) for artifact in task.artifacts],
                "messageIds": [message.message_id for message in task.history]}

    requests = []

    async def observe_request(request):
        # Observe SDK-produced framing; never construct a JSON-RPC envelope.
        if request.url.host != "127.0.0.1" or request.url.port != port:
            raise RuntimeError("The lab only permits its own loopback listener.")
        record = {"httpMethod": request.method, "path": request.url.path}
        if request.method == "POST":
            body = json.loads(request.content)
            record.update({"jsonrpc": body["jsonrpc"], "rpcMethod": body["method"], "requestId": body["id"]})
            message = body.get("params", {}).get("message")
            if message:
                record["message"] = message
        requests.append(record)

    async def observe_response(response):
        requests[-1]["httpStatus"] = response.status_code

    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.bind(("127.0.0.1", 0))
    listener.listen(16)
    listener.setblocking(False)
    port = listener.getsockname()[1]
    base_url = f"http://127.0.0.1:{port}"
    card = AgentCard(
        name="Synthetic review-date specialist", description="Reads one fictional procedure date; no model or authentication.",
        version="1.0.0", default_input_modes=["text/plain"], default_output_modes=["text/plain", "application/json"],
        capabilities=AgentCapabilities(streaming=False),
        supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", protocol_version="1.0", url=base_url + "/rpc")],
        skills=[AgentSkill(id="synthetic-review-date", name="Read a review date",
                           description="Return the supplied P-17 fixture after clarification.", tags=["synthetic"])])
    handler = DefaultRequestHandler(agent_executor=ReviewDateExecutor(), task_store=InMemoryTaskStore(), agent_card=card)
    app = Starlette(routes=[*create_agent_card_routes(card), *create_jsonrpc_routes(handler, "/rpc")])
    server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_config=None,
                                          log_level="critical", access_log=False, lifespan="off",
                                          timeout_graceful_shutdown=1))
    serving = asyncio.create_task(server.serve(sockets=[listener]))
    try:
        async with asyncio.timeout(3):
            while not server.started:
                if serving.done():
                    await serving
                    raise RuntimeError("The loopback server stopped before startup.")
                await asyncio.sleep(0.01)
        async with httpx.AsyncClient(trust_env=False, timeout=5, follow_redirects=False,
                                     event_hooks={"request": [observe_request], "response": [observe_response]}) as http, AsyncExitStack() as resources:
            discovered = await A2ACardResolver(http, base_url).get_agent_card()
            client = ClientFactory(ClientConfig(streaming=False, httpx_client=http,
                                                 supported_protocol_bindings=["JSONRPC"])).create(discovered)
            resources.push_async_callback(client.close)

            async def send(message):
                task = None
                async for event in client.send_message(SendMessageRequest(message=message)):
                    if event.HasField("task"):
                        task = event.task
                if task is None:
                    raise RuntimeError("Expected an SDK task response, not a message-only response.")
                return task

            first_message = new_text_message("Find the review due date in the procedure.", role=Role.ROLE_USER)
            first = snapshot(await send(first_message))
            follow_up = new_text_message("Use procedure P-17.", role=Role.ROLE_USER,
                                         task_id=first["id"], context_id=first["contextId"])
            completed = snapshot(await send(follow_up))
            stored = snapshot(await client.get_task(GetTaskRequest(id=first["id"])))
            return {"scenario": scenario, "mode": "A2A SDK over real loopback JSON-RPC HTTP",
                    "sdkVersion": installed["a2a-sdk"], "packages": installed,
                    "agentCard": MessageToDict(discovered), "source": dict(SOURCE),
                    "initialMessage": MessageToDict(first_message), "initialTask": first,
                    "sentMessage": MessageToDict(follow_up), "completedTask": completed,
                    "storedTask": stored, "clientDecision": validate_artifact(stored, first),
                    "requests": requests,
                    "limits": {"modelCalls": 0, "authenticated": False, "persistentStore": False,
                               "store": "SDK InMemoryTaskStore", "listener": "127.0.0.1", "port": port}}
    finally:
        server.should_exit = True
        try:
            await asyncio.wait_for(asyncio.shield(serving), timeout=3)
        except TimeoutError:
            serving.cancel()
            with suppress(asyncio.CancelledError):
                await serving
        finally:
            await handler.aclose()
            listener.close()


async def compare(names):
    # Bound the whole experiment as well as individual HTTP calls and shutdown.
    async with asyncio.timeout(25):
        return {"synthetic": True, "results": [await run_case(name) for name in names]}


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("scenario", choices=("compare", "check", *SCENARIOS), nargs="?", default="compare")
    args = parser.parse_args()
    try:
        report = check() if args.scenario == "check" else asyncio.run(compare(SCENARIOS if args.scenario == "compare" else (args.scenario,)))
        print(json.dumps(report, indent=2))
    except (RuntimeError, TimeoutError) as error:
        print(f"Lab stopped: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
