"""The same Currency Agent, built on the official A2A Python SDK (a2a-sdk 1.3.0).

Compare with raw_server.py. The SDK owns JSON-RPC parsing, SSE, the task
store, and the state machine. You write one AgentExecutor class.

Run:  python src/a2a_lab/sdk_server.py --port 10000
"""

from __future__ import annotations

import argparse
import logging

import uvicorn
from a2a.helpers import get_message_text, new_data_part, new_task, new_text_part
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
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,
    Message,
    Role,
    TaskState,
)
from starlette.applications import Starlette

if __package__:
    from a2a_lab import currency_rules as rules
else:  # Run as a plain script.
    import currency_rules as rules

logger = logging.getLogger(__name__)
RPC_PATH = "/a2a/v1"


def build_card(base_url: str) -> AgentCard:
    """The same public Agent Card as raw_server.py, as a typed proto object."""
    return AgentCard(
        name="Currency Agent (SDK)",
        description="Converts money between USD, EUR, GBP, INR, and JPY.",
        version="1.0.0",
        supported_interfaces=[AgentInterface(
            url=base_url + RPC_PATH, protocol_binding="JSONRPC", protocol_version="1.0")],
        capabilities=AgentCapabilities(streaming=True),
        default_input_modes=["text/plain"],
        default_output_modes=["text/plain", "application/json"],
        skills=[AgentSkill(
            id="convert_currency", name="Convert currency",
            description="Convert an amount from one currency to another.",
            tags=["finance", "currency"],
            examples=["Convert 100 USD to EUR"])],
    )


def understood_so_far(history: list[Message], latest: Message) -> rules.Request:
    """Rebuild what the user asked from every user turn in the task.

    The executor keeps no state of its own. The SDK's task store holds the
    history, so any server replica can pick up the next turn.
    """
    request = rules.Request()
    seen: set[str] = set()
    for message in [*history, latest]:
        if message.role == Role.ROLE_USER and message.message_id not in seen:
            seen.add(message.message_id)
            request = request.merge(rules.parse(get_message_text(message)))
    return request


class CurrencyAgentExecutor(AgentExecutor):
    """All agent logic lives here. The SDK calls execute() once per message."""

    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        """Publish a Task, then status and artifact events to the queue."""
        assert context.message is not None and context.task_id and context.context_id
        task = context.current_task
        if task is None:
            task = new_task(context.task_id, context.context_id,
                            TaskState.TASK_STATE_SUBMITTED, history=[context.message])
            await event_queue.enqueue_event(task)
        updater = TaskUpdater(event_queue, context.task_id, context.context_id)
        await updater.start_work()
        request = understood_so_far(list(task.history), context.message)
        question = request.missing_question()
        if question is not None:
            await updater.requires_input(updater.new_agent_message([new_text_part(question)]))
            return
        await updater.add_artifact(
            [new_text_part(rules.answer(request)),
             new_data_part({"result": str(rules.convert(request)), "to": request.target})],
            name="conversion")
        await updater.complete()

    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        """Mark the task canceled. This agent has no background work to stop."""
        assert context.task_id and context.context_id
        await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()


def build_app(base_url: str) -> Starlette:
    """Wire the executor, task store, and routes into one ASGI app."""
    card = build_card(base_url)
    handler = DefaultRequestHandler(
        agent_executor=CurrencyAgentExecutor(),
        task_store=InMemoryTaskStore(),
        agent_card=card,
    )
    routes = [*create_agent_card_routes(card), *create_jsonrpc_routes(handler, RPC_PATH)]
    return Starlette(routes=routes)


def main() -> None:
    """Parse flags and serve with uvicorn until Ctrl+C."""
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--port", type=int, default=10000)
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)
    uvicorn.run(build_app(f"http://localhost:{args.port}"), host="127.0.0.1",
                port=args.port, log_level="warning")


if __name__ == "__main__":
    main()
