"""Colony escalation — Telegram notifications for governance events."""

from __future__ import annotations

import os

import httpx
import structlog

log = structlog.get_logger()

TELEGRAM_API = "https://api.telegram.org"


async def send_escalation(chat_id: str, message: str) -> bool:
    """Send a Telegram notification. Returns True on success."""
    bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
    if not bot_token or not chat_id:
        log.warning("colony.escalation_skipped", reason="no telegram config")
        return False

    url = f"{TELEGRAM_API}/bot{bot_token}/sendMessage"
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.post(
                url,
                json={"chat_id": chat_id, "text": message, "parse_mode": "Markdown"},
            )
        if resp.status_code == 200:
            return True
        log.warning("colony.escalation_failed", status=resp.status_code, body=resp.text[:200])
    except httpx.HTTPError as e:
        log.warning("colony.escalation_error", error=str(e))
    return False


async def notify_started(
    chat_id: str, branch: str, duration_hours: float, mission: str = "",
) -> None:
    mission_line = f"\nMission: {mission}" if mission else ""
    await send_escalation(
        chat_id,
        f"*Colony experiment started*\nBranch: `{branch}`\nDuration: {duration_hours}h{mission_line}",
    )


async def notify_proposal_escalated(
    chat_id: str, proposal_id: str, title: str, reason: str
) -> None:
    await send_escalation(
        chat_id,
        f"*Colony escalation*\n`{proposal_id}`: {title}\nReason: {reason}",
    )


async def notify_complete(chat_id: str, summary: str) -> None:
    await send_escalation(chat_id, f"*Colony experiment complete*\n{summary}")
