import json

from temporalio import workflow

from terminaluse.lib import adk
from terminaluse.lib.types.acp import CreateTaskParams, SendEventParams
from terminaluse.lib.core.temporal.workflows.workflow import BaseWorkflow
from terminaluse.lib.core.temporal.types.workflow import SignalName
from terminaluse.lib.utils.logging import make_logger
from terminaluse.types.task_message_content import TaskMessageContent_Text
from terminaluse.lib.environment_variables import EnvironmentVariables

environment_variables = EnvironmentVariables.refresh()

if environment_variables.TERMINALUSE_WORKFLOW_NAME is None:
    raise ValueError("Environment variable TERMINALUSE_WORKFLOW_NAME is not set")

if environment_variables.TERMINALUSE_AGENT_NAME is None:
    raise ValueError("Environment variable TERMINALUSE_AGENT_NAME is not set")

logger = make_logger(__name__)

@workflow.defn(name=environment_variables.TERMINALUSE_WORKFLOW_NAME)
class {{ workflow_class }}(BaseWorkflow):
    """
    Minimal async workflow template for TerminalUse Temporal agents.
    """
    def __init__(self):
        super().__init__(display_name=environment_variables.TERMINALUSE_AGENT_NAME)
        self._complete_task = False

    @workflow.signal(name=SignalName.RECEIVE_EVENT)
    async def on_event(self, params: SendEventParams) -> None:
        logger.info(f"Received task message instruction: {params}")

        # 2. Echo back the client's message to show it in the UI. This is not done by default so the agent developer has full control over what is shown to the user.
        await adk.messages.send(task_id=params.task.id, content=params.event.content)

        # 3. Send a simple response message.
        # In future tutorials, this is where we'll add more sophisticated response logic.
        await adk.messages.send(
            task_id=params.task.id,
            content=TaskMessageContent_Text(
                author="agent",
                content=f"Hello! I've received your message. I can't respond right now, but in future tutorials we'll see how you can get me to intelligently respond to your message.",
            ),
        )

    @workflow.run
    async def on_create(self, params: CreateTaskParams) -> str:
        logger.info(f"Received task create params: {params}")

        # 1. Acknowledge that the task has been created.
        await adk.messages.send(
            task_id=params.task.id,
            content=TaskMessageContent_Text(
                author="agent",
                content=f"Hello! I've received your task. Normally you can do some state initialization here, or just pass and do nothing until you get your first event. For now I'm just acknowledging that I've received a task with the following params:\n\n{json.dumps(params.params, indent=2)}.\n\nYou should only see this message once, when the task is created. All subsequent events will be handled by the `on_event` handler.",
            ),
        )

        await workflow.wait_condition(
            lambda: self._complete_task,
            timeout=None, # Set a timeout if you want to prevent the task from running indefinitely. Generally this is not needed. Temporal can run hundreds of millions of workflows in parallel and more. Only do this if you have a specific reason to do so.
        )
        return "Task completed"
