# ClawTex — Governed Agent with Genetic Memory
# Built by DeVere Cooley / AN2B LLC · an2b.com
# BB4C — Breath Before Code

"""
Telegram channel adapter — connects a ClawTex agent to a Telegram bot.

Requires: TELEGRAM_BOT_TOKEN env var and python-telegram-bot >= 20.x

Usage:
    channel = TelegramChannel(handler=agent.handle_message)
    await channel.start()          # begins polling
"""

from __future__ import annotations

import logging
import os
from typing import Any

from .base import BaseChannel, InboundMessage, MessageHandler, OutboundMessage

logger = logging.getLogger(__name__)


class TelegramChannel(BaseChannel):
    """Telegram bot channel using python-telegram-bot (v20+ async API)."""

    name = "telegram"

    def __init__(self, handler: MessageHandler, token: str | None = None) -> None:
        super().__init__(handler)
        self._token = token or os.environ.get("TELEGRAM_BOT_TOKEN", "")
        self._app: Any = None

    async def start(self) -> None:
        if not self._token:
            raise ValueError(
                "TELEGRAM_BOT_TOKEN is not set. "
                "Set it in your .env file to enable the Telegram channel."
            )

        try:
            from telegram import Update
            from telegram.ext import Application, ContextTypes, MessageHandler as TGMsgHandler, filters
        except ImportError as exc:
            raise ImportError(
                "python-telegram-bot is not installed. "
                "Run: pip install python-telegram-bot"
            ) from exc

        self._app = Application.builder().token(self._token).build()

        async def _on_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
            if not update.message or not update.message.text:
                return
            msg = InboundMessage(
                text=update.message.text,
                user_id=str(update.effective_user.id),
                channel=self.name,
                thread_id=str(update.message.chat_id),
                metadata={
                    "chat_id": update.message.chat_id,
                    "username": update.effective_user.username,
                },
            )
            reply_text = await self.handle(msg)
            await update.message.reply_text(reply_text)

        self._app.add_handler(TGMsgHandler(filters.TEXT & ~filters.COMMAND, _on_message))
        self._running = True
        logger.info("Telegram channel starting (polling)…")
        await self._app.run_polling()

    async def stop(self) -> None:
        self._running = False
        if self._app:
            await self._app.stop()
            logger.info("Telegram channel stopped.")

    async def send(self, message: OutboundMessage) -> None:
        if not self._app:
            logger.warning("Telegram send called before start()")
            return
        chat_id = message.metadata.get("chat_id") or message.user_id
        await self._app.bot.send_message(chat_id=chat_id, text=message.text)
