import asyncio

import a2a
from a2a_acl.message_tools import acl_message

import context

from a2a.types import (
    AgentCard,
)

from a2a_acl.a2a_utils.send_message import (
    extract_text_from_task_artifact,
)
from a2a_acl.message_tools.send_acl_message import (
    spawn_send_acl_message,
)
from a2a_acl.a2a_utils.card_holder import download_card


from a2a_acl.utils.url import build_url

from a2a_agentspeak.content_codecs.common import python_agentspeak_codec_id

def handle_status_update(e, t, m):
    match type(t):
        case a2a.types.TaskStatusUpdateEvent:
            print("(status update: " + str(t.status.state) + ")")
        case _:
            print("(status update ignored)")

current_async_tasks = []

async def main() -> None:
    target_agent_url = build_url(context.host, context.generator_port)

    # Fetch Public Agent Card and Initialize Client
    target_agent_card: AgentCard | None = None

    try:
        target_agent_card = await download_card(target_agent_url)

    except Exception:
        print("Client failed to fetch the public agent card. Cannot continue.")
        exit(-1)

    print("end")

    spawn_send_acl_message(
        target_agent_card,
        acl_message.TELL,
        'spec("A function to reverse the order of the elements of a list.")',
        "",
        python_agentspeak_codec_id,
    )
    print("[Tell-Message sent to validator agent.]")

    await asyncio.sleep(0.5)

    spawn_send_acl_message(
        target_agent_card,
        acl_message.ACHIEVE,
        "build.",
        "",
        codec = python_agentspeak_codec_id,
        artifact_update_callback=(
            lambda t: print("Artifact received: " + extract_text_from_task_artifact(t))
        ),
        status_update_callback=handle_status_update,
    )
    print("[Request-Message sent to validator agent.]")


if __name__ == "__main__":

    asyncio.run(main())
    input("Press Enter to exit.\n")
