from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..client import WhatsrbCloud
    from .agent_run import AgentRun


class Agent:
    def __init__(self, data: dict, *, client: WhatsrbCloud | None = None):
        self.id = data.get("id")
        self.name = data.get("name")
        self.description = data.get("description")
        self.system_prompt = data.get("system_prompt")
        self.model = data.get("model")
        self.temperature = data.get("temperature")
        self.max_tokens = data.get("max_tokens")
        self.active = data.get("active")
        self.auto_run_inbound = data.get("auto_run_inbound")
        self.debounce_seconds = data.get("debounce_seconds")
        self.context_ttl_minutes = data.get("context_ttl_minutes")
        self.inbound_config = data.get("inbound_config")
        self.payload_schema = data.get("payload_schema")
        self.allowed_actions = data.get("allowed_actions", [])
        self.tools = data.get("tools")
        self.business_account_id = data.get("business_account_id")
        self.created_at = data.get("created_at")
        self.updated_at = data.get("updated_at")
        self._client = client
        self._raw = data

    @property
    def is_active(self) -> bool:
        return self.active is True

    @property
    def is_auto_run(self) -> bool:
        return self.auto_run_inbound is True

    def run(self, *, input, metadata: dict | None = None, timeout: int = 30, interval: int = 1) -> AgentRun:
        return self.run_async(input=input, metadata=metadata).wait(timeout=timeout, interval=interval)

    def run_async(self, *, input, metadata: dict | None = None) -> AgentRun:
        return self.runs().create(input=input, metadata=metadata)

    def runs(self):
        return self._client.agent_runs(self.id)

    def reload(self) -> Agent:
        refreshed = self._client.agents.retrieve(self.id)
        self.name = refreshed.name
        self.description = refreshed.description
        self.system_prompt = refreshed.system_prompt
        self.model = refreshed.model
        self.temperature = refreshed.temperature
        self.max_tokens = refreshed.max_tokens
        self.active = refreshed.active
        self.auto_run_inbound = refreshed.auto_run_inbound
        self.debounce_seconds = refreshed.debounce_seconds
        self.inbound_config = refreshed.inbound_config
        self.payload_schema = refreshed.payload_schema
        self.allowed_actions = refreshed.allowed_actions
        self.tools = refreshed.tools
        self.updated_at = refreshed.updated_at
        return self

    def refresh(self) -> Agent:
        return self.reload()

    def to_dict(self) -> dict:
        return self._raw
