"""AgentStack: encapsulates a complete bot stack for one agent."""

from __future__ import annotations

import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING

from klir.config import AgentConfig
from klir.workspace.init import init_workspace
from klir.workspace.paths import KlirPaths, resolve_paths

if TYPE_CHECKING:
    from klir.bot.app import TelegramBot

logger = logging.getLogger(__name__)


@dataclass
class AgentStack:
    """Container for one agent's entire bot stack.

    Each agent gets its own TelegramBot → Orchestrator → CLIService pipeline,
    its own workspace, sessions, cron jobs, and webhooks.
    """

    name: str
    config: AgentConfig
    paths: KlirPaths
    bot: TelegramBot
    is_main: bool = False

    @classmethod
    async def create(
        cls,
        name: str,
        config: AgentConfig,
        *,
        is_main: bool = False,
    ) -> AgentStack:
        """Factory: initialize workspace and create TelegramBot.

        The workspace is seeded (Zone 2 + 3) and the TelegramBot created,
        but polling is NOT started yet — call ``run()`` for that.
        """
        import asyncio

        paths = resolve_paths(klir_home=config.klir_home)
        await asyncio.to_thread(init_workspace, paths)

        from klir.bot.app import TelegramBot

        bot = TelegramBot(config, agent_name=name)
        logger.info(
            "AgentStack created: name=%s home=%s main=%s",
            name,
            paths.klir_home,
            is_main,
        )
        return cls(name=name, config=config, paths=paths, bot=bot, is_main=is_main)

    async def run(self) -> int:
        """Start the Telegram bot (blocks until stop/crash).

        Returns exit code (0 = normal, 42 = restart requested).
        """
        return await self.bot.run()

    async def shutdown(self) -> None:
        """Gracefully shut down the bot and all observers."""
        await self.bot.shutdown()
        logger.info("AgentStack '%s' shut down", self.name)
