"""A from-scratch A2A v1.0 server using only the Python standard library.

Nothing here is hidden behind an SDK, so you can read every byte of the
protocol: the Agent Card, JSON-RPC 2.0 methods, the Task state machine,
multi-turn INPUT_REQUIRED, and Server-Sent Events (SSE) streaming.

Run:  python src/a2a_lab/raw_server.py --port 9999
Then: python src/a2a_lab/raw_client.py --url http://localhost:9999
"""

from __future__ import annotations

import argparse
import json
import logging
import threading
import time
import uuid
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any

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__)

AGENT_CARD_PATH = "/.well-known/agent-card.json"
RPC_PATH = "/a2a/v1"
TERMINAL = {"TASK_STATE_COMPLETED", "TASK_STATE_FAILED", "TASK_STATE_CANCELED",
            "TASK_STATE_REJECTED"}

# JSON-RPC error codes from A2A spec sections 5.4 and 9.5.
METHOD_NOT_FOUND = -32601
INVALID_PARAMS = -32602
TASK_NOT_FOUND = -32001
TASK_NOT_CANCELABLE = -32002
UNSUPPORTED_OPERATION = -32004

Json = dict[str, Any]


class RpcError(Exception):
    """A JSON-RPC error that the server returns to the caller."""

    def __init__(self, code: int, message: str) -> None:
        super().__init__(message)
        self.code = code


def agent_card(base_url: str) -> Json:
    """Build the public Agent Card: the agent's "business card" for discovery."""
    return {
        "name": "Currency Agent",
        "description": "Converts money between USD, EUR, GBP, INR, and JPY.",
        "version": "1.0.0",
        "supportedInterfaces": [
            {"url": base_url + RPC_PATH, "protocolBinding": "JSONRPC",
             "protocolVersion": "1.0"},
        ],
        "provider": {"organization": "CatZep Lab", "url": "https://example.com"},
        "capabilities": {"streaming": True, "pushNotifications": False},
        "defaultInputModes": ["text/plain"],
        "defaultOutputModes": ["text/plain", "application/json"],
        "skills": [{
            "id": "convert_currency",
            "name": "Convert currency",
            "description": "Convert an amount from one currency to another. "
                           "Asks a follow-up question when details are missing.",
            "tags": ["finance", "currency"],
            "examples": ["Convert 100 USD to EUR", "How much is 50 GBP in INR?"],
        }],
    }


def text_message(role: str, text: str, *, task: Json | None = None) -> Json:
    """Build a Message with one text Part. Agent messages carry task IDs."""
    message: Json = {"messageId": str(uuid.uuid4()), "role": role,
                     "parts": [{"text": text}]}
    if task is not None:
        message["taskId"] = task["id"]
        message["contextId"] = task["contextId"]
    return message


class CurrencyAgentServer:
    """Holds tasks in memory and runs the agent logic for each message.

    One lock guards all task state. Each handler thread holds it only while
    reading or changing a task, never while sleeping between stream events.
    """

    def __init__(self, *, step_delay: float = 0.0) -> None:
        self._tasks: dict[str, Json] = {}
        self._understood: dict[str, rules.Request] = {}
        self._lock = threading.Lock()
        self._step_delay = step_delay

    def dispatch(self, method: str, params: Json) -> Json:
        """Route a non-streaming JSON-RPC call to its handler."""
        handlers = {"SendMessage": self.send_message, "GetTask": self.get_task,
                    "CancelTask": self.cancel_task, "ListTasks": self.list_tasks}
        if method not in handlers:
            raise RpcError(METHOD_NOT_FOUND, f"Method not found: {method}")
        return handlers[method](params)

    def send_message(self, params: Json) -> Json:
        """SendMessage: run every step, then return the final Task snapshot."""
        task, steps = self._start(params)
        for _ in steps:
            pass
        return {"task": self._snapshot(task["id"])}

    def stream_message(self, params: Json) -> Iterator[Json]:
        """SendStreamingMessage: yield one StreamResponse per state change."""
        task, steps = self._start(params)
        yield {"task": self._snapshot(task["id"])}
        for event in steps:
            time.sleep(self._step_delay)
            yield event

    def get_task(self, params: Json) -> Json:
        """GetTask: return the current Task. Clients poll with this."""
        return self._snapshot(self._require_id(params))

    def list_tasks(self, params: Json) -> Json:
        """ListTasks: return tasks, optionally filtered by contextId."""
        context_id = params.get("contextId")
        with self._lock:
            ids = [t["id"] for t in self._tasks.values()
                   if context_id in (None, t["contextId"])]
        return {"tasks": [self._snapshot(i) for i in ids]}

    def cancel_task(self, params: Json) -> Json:
        """CancelTask: only a task that has not finished can be canceled."""
        task_id = self._require_id(params)
        with self._lock:
            task = self._tasks[task_id]
            if task["status"]["state"] in TERMINAL:
                raise RpcError(TASK_NOT_CANCELABLE, f"Task {task_id} already finished")
            task["status"] = {"state": "TASK_STATE_CANCELED"}
        return self._snapshot(task_id)

    def _require_id(self, params: Json) -> str:
        task_id = params.get("id")
        if not isinstance(task_id, str):
            raise RpcError(INVALID_PARAMS, "params.id must be a task ID string")
        with self._lock:
            if task_id not in self._tasks:
                raise RpcError(TASK_NOT_FOUND, f"Task not found: {task_id}")
        return task_id

    def _snapshot(self, task_id: str) -> Json:
        with self._lock:
            return json.loads(json.dumps(self._tasks[task_id]))

    def _start(self, params: Json) -> tuple[Json, Iterator[Json]]:
        """Validate the message, find or create its Task, and plan the steps."""
        message = params.get("message")
        if not isinstance(message, dict) or not message.get("parts"):
            raise RpcError(INVALID_PARAMS, "params.message with parts is required")
        task = self._find_or_create(message)
        return task, self._run(task, message)

    def _find_or_create(self, message: Json) -> Json:
        task_id = message.get("taskId")
        with self._lock:
            if task_id is None:
                task = {"id": str(uuid.uuid4()),
                        "contextId": message.get("contextId") or str(uuid.uuid4()),
                        "status": {"state": "TASK_STATE_SUBMITTED"}, "history": []}
                self._tasks[task["id"]] = task
                self._understood[task["id"]] = rules.Request()
            elif task_id not in self._tasks:
                raise RpcError(TASK_NOT_FOUND, f"Task not found: {task_id}")
            else:
                task = self._tasks[task_id]
                if task["status"]["state"] != "TASK_STATE_INPUT_REQUIRED":
                    raise RpcError(UNSUPPORTED_OPERATION,
                                   f"Task {task_id} is not waiting for input")
            task["history"].append(message)
        return task

    def _run(self, task: Json, message: Json) -> Iterator[Json]:
        """The agent logic. A generator, so streaming can send each step live."""
        yield self._set_state(task, "TASK_STATE_WORKING")
        text = " ".join(p.get("text", "") for p in message["parts"])
        with self._lock:
            request = self._understood[task["id"]].merge(rules.parse(text))
            self._understood[task["id"]] = request
        question = request.missing_question()
        if question is not None:
            reply = text_message("ROLE_AGENT", question, task=task)
            yield self._set_state(task, "TASK_STATE_INPUT_REQUIRED", reply)
            return
        yield self._add_artifact(task, request)
        yield self._set_state(task, "TASK_STATE_COMPLETED")

    def _set_state(self, task: Json, state: str, message: Json | None = None) -> Json:
        status: Json = {"state": state}
        if message is not None:
            status["message"] = message
        with self._lock:
            if task["status"]["state"] == "TASK_STATE_CANCELED":
                status = task["status"]  # A cancel won the race. Keep it.
            task["status"] = status
        return {"statusUpdate": {"taskId": task["id"], "contextId": task["contextId"],
                                 "status": status}}

    def _add_artifact(self, task: Json, request: rules.Request) -> Json:
        artifact = {
            "artifactId": str(uuid.uuid4()), "name": "conversion",
            "parts": [
                {"text": rules.answer(request)},
                {"data": {"amount": str(request.amount), "from": request.source,
                          "to": request.target, "result": str(rules.convert(request))},
                 "mediaType": "application/json"},
            ],
        }
        with self._lock:
            task.setdefault("artifacts", []).append(artifact)
        return {"artifactUpdate": {"taskId": task["id"], "contextId": task["contextId"],
                                   "artifact": artifact, "lastChunk": True}}


def make_handler(agent: CurrencyAgentServer) -> type[BaseHTTPRequestHandler]:
    """Bind the agent to an HTTP handler class for ThreadingHTTPServer."""

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self) -> None:
            if self.path != AGENT_CARD_PATH:
                self.send_error(404)
                return
            base = f"http://{self.headers.get('Host', 'localhost')}"
            self._send_json(200, agent_card(base))

        def do_POST(self) -> None:
            if self.path != RPC_PATH:
                self.send_error(404)
                return
            length = int(self.headers.get("Content-Length", "0"))
            try:
                call = json.loads(self.rfile.read(length))
            except json.JSONDecodeError:
                self._send_json(200, _error(None, -32700, "Invalid JSON payload"))
                return
            call_id, params = call.get("id"), call.get("params") or {}
            if call.get("method") == "SendStreamingMessage":
                self._stream(call_id, params)
                return
            try:
                result = agent.dispatch(call.get("method", ""), params)
                self._send_json(200, {"jsonrpc": "2.0", "id": call_id, "result": result})
            except RpcError as err:
                self._send_json(200, _error(call_id, err.code, str(err)))

        def _stream(self, call_id: Any, params: Json) -> None:
            try:
                events = agent.stream_message(params)
                first = next(events)
            except RpcError as err:
                self._send_json(200, _error(call_id, err.code, str(err)))
                return
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Cache-Control", "no-cache")
            self.end_headers()
            for event in (first, *events):
                frame = {"jsonrpc": "2.0", "id": call_id, "result": event}
                self.wfile.write(f"data: {json.dumps(frame)}\n\n".encode())
                self.wfile.flush()
            self.close_connection = True

        def _send_json(self, code: int, body: Json) -> None:
            data = json.dumps(body).encode()
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def log_message(self, fmt: str, *args: Any) -> None:
            logger.info("%s %s", self.address_string(), fmt % args)

    return Handler


def _error(call_id: Any, code: int, message: str) -> Json:
    return {"jsonrpc": "2.0", "id": call_id, "error": {"code": code, "message": message}}


def serve(port: int, *, step_delay: float = 0.4) -> ThreadingHTTPServer:
    """Create (but do not start) the HTTP server. Port 0 picks a free port."""
    agent = CurrencyAgentServer(step_delay=step_delay)
    return ThreadingHTTPServer(("127.0.0.1", port), make_handler(agent))


def main() -> None:
    """Parse flags and serve until Ctrl+C."""
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--port", type=int, default=9999)
    parser.add_argument("--step-delay", type=float, default=0.4,
                        help="Seconds between streamed events, to make streaming visible.")
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    server = serve(args.port, step_delay=args.step_delay)
    logger.info("Currency Agent card: http://localhost:%d%s", args.port, AGENT_CARD_PATH)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()


if __name__ == "__main__":
    main()
