"""Public A2A 1.0 example. No API key, cookies or browser required.

python3 kroner-agent-client.py "Wie läuft der Richtungsworkshop ab?"
Add --followup "..." for a second question in the same conversation.
Do not send personal or confidential information.
"""
import argparse
import json
import urllib.request
import uuid

BASE = "https://www.markus-kroner.com"
HEADERS = {
    "User-Agent": "KronerAgentClient/1.1 (+https://www.markus-kroner.com/ki-agenten)",
    "Accept": "application/json",
    "A2A-Version": "1.0",
}


def exchange(url, body=None):
    request = urllib.request.Request(
        url,
        data=json.dumps(body).encode("utf-8") if body is not None else None,
        headers={**HEADERS, **({"Content-Type": "application/json"} if body is not None else {})},
    )
    with urllib.request.urlopen(request, timeout=35) as response:
        result = json.load(response)
    if "error" in result:
        raise RuntimeError(result["error"])
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("question")
    parser.add_argument("--followup")
    args = parser.parse_args()
    card = exchange(BASE + "/.well-known/agent-card.json")
    supported = card.get("supportedInterfaces", [])
    endpoint = next(
        (interface["url"] for interface in supported
         if interface.get("protocolBinding") == "JSONRPC" and interface.get("protocolVersion") == "1.0"),
        None,
    )
    if endpoint != BASE + "/api/a2a":
        raise RuntimeError("Unexpected agent endpoint")
    context = None
    for text in filter(None, [args.question, args.followup]):
        message = {"role": "ROLE_USER", "messageId": str(uuid.uuid4()), "parts": [{"text": text}]}
        if context:
            message["contextId"] = context
        result = exchange(endpoint, {"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": "SendMessage", "params": {"message": message}})
        reply = result["result"]["message"]
        context = reply["contextId"]
        print(json.dumps({"question": text, "parts": reply["parts"]}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
