"""Demo Agent 2: Translator Agent -- server only, called by the Orchestrator.
Canned translation table, not a real translation service -- a throwaway
test fixture to prove the A2A chain, same as the weather agent.
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))

import uvicorn
from a2a.helpers import get_data_parts, new_data_part, new_task_from_user_message
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.tasks import TaskUpdater
from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill
from a2a.types.a2a_pb2 import TaskState

from a2a_passport import build_agent_app
from a2a_passport.auth.verifiers import SharedSecretVerifier
from a2a_passport.testing import JWT_SECRET

PORT = 9202
AUDIENCE = "translator-agent"
REQUIRED_SCOPE = "translator:use"

_CANNED_TRANSLATIONS = {
    ("light rain", "french"): "pluie légère",
    ("humid, partly cloudy", "japanese"): "湿気が多く、一部曇り",
    ("clear", "hindi"): "साफ़",
}


class TranslatorExecutor(AgentExecutor):
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        task = context.current_task or new_task_from_user_message(context.message)
        if not context.current_task:
            await event_queue.enqueue_event(task)
        updater = TaskUpdater(event_queue=event_queue, task_id=task.id, context_id=task.context_id)
        await updater.update_status(state=TaskState.TASK_STATE_WORKING)

        incoming = get_data_parts(context.message.parts)
        request = incoming[0] if incoming else {}
        text = str(request.get("text", "")).strip().lower()
        target = str(request.get("target_language", "")).strip().lower()
        translated = _CANNED_TRANSLATIONS.get(
            (text, target), f"[no canned translation for '{text}' -> {target}]"
        )

        result = {
            "original_text": request.get("text"),
            "target_language": request.get("target_language"),
            "translated_text": translated,
        }
        await updater.add_artifact(parts=[new_data_part(data=result)], name="translation_result")
        await updater.update_status(state=TaskState.TASK_STATE_COMPLETED)

    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        raise NotImplementedError("cancel is not supported by the translator agent demo")


def build_app():
    skill = AgentSkill(
        id="translate_text",
        name="Translate Text",
        description="Translates a short piece of text into a target language.",
        input_modes=["application/json"],
        output_modes=["application/json"],
        tags=["demo", "translation"],
        examples=['{"text": "clear", "target_language": "Hindi"}'],
    )
    card = AgentCard(
        name="Translator Agent",
        description="Demo agent providing canned translations.",
        version="0.1.0",
        default_input_modes=["application/json"],
        default_output_modes=["application/json"],
        capabilities=AgentCapabilities(streaming=False),
        supported_interfaces=[AgentInterface(protocol_binding="JSONRPC", url=f"http://127.0.0.1:{PORT}")],
        skills=[skill],
    )
    return build_agent_app(
        card=card,
        executor=TranslatorExecutor(),
        verifier=SharedSecretVerifier(JWT_SECRET),
        expected_audience=AUDIENCE,
        required_scope=REQUIRED_SCOPE,
        service_name="translator-agent",
    )


if __name__ == "__main__":
    uvicorn.run(build_app(), host="127.0.0.1", port=PORT)
