"""Protocol adapter for inbound/outbound message normalization."""

from __future__ import annotations

import json
import time
import uuid
from typing import Callable, Optional, Any, Dict


class ProtocolAdapter:
    """Handles multi-protocol decoding and receipt formatting."""

    def __init__(self, send_task: Callable[..., Any]):
        self._send_task = send_task

    def receive_message(self, message: Any, priority: int = 2, complexity: int = 5, ttl: float = 10):
        """Decodes FIPA, KQML, JSON-RPC and Simple Text.

        Returns:
            Task ID in queue.
        """
        protocol = "SIMPLE"
        m_id = str(uuid.uuid4())[:8]
        task = str(message)

        if isinstance(message, dict):
            # FIPA ACL
            if "performative" in message:
                protocol = "FIPA"
                m_id = message.get("conversation-id", m_id)
                task = f"[{message['performative'].upper()}] {message['content']}"
            # KQML
            elif "verb" in message:
                protocol = "KQML"
                m_id = message.get("reply-with", m_id)
                task = f"[{message['verb'].upper()}] {message['content']}"
            # JSON-RPC
            elif "jsonrpc" in message:
                protocol = "JSON-RPC"
                m_id = str(message.get("id", m_id))
                task = f"[METHOD:{message.get('method')}] {json.dumps(message.get('params', {}))}"

        return self._send_task(task, priority, complexity, ttl, m_id, protocol)

    def create_receipt(
        self,
        m_id: str,
        status: str,
        result: Any,
        t_arrival: float,
        t_start: float,
        proto: str,
        correlation_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        """Encapsulates response in original protocol with correlation ID."""
        core: Dict[str, Any] = {
            "mission_id": m_id,
            "status": status,
            "result": result,
            "wait": round(t_start - t_arrival, 4),
            "execution": round(time.time() - t_start, 4),
        }
        if correlation_id:
            core["correlation_id"] = correlation_id
        if proto == "FIPA":
            return {"performative": "inform", "content": core, "conversation-id": m_id}
        if proto == "KQML":
            return {"verb": "tell", "content": core, "reply-with": m_id}
        if proto == "JSON-RPC":
            return {"jsonrpc": "2.0", "result": core, "id": m_id}
        return core
