"""
Send Telegram notifications for hyperagent events.
Owner gets informed when skills are improved or rolled back.
"""

import json
import urllib.request
from pathlib import Path


def notify_owner(message: str):
    """Send a Telegram message to the device owner about hyperagent activity."""
    env_file = Path.home() / "hermes-agent" / ".env"
    token = ""
    chat_id = ""

    # Get bot token
    if env_file.exists():
        for line in env_file.read_text().splitlines():
            if line.startswith("TELEGRAM_BOT_TOKEN="):
                token = line.split("=", 1)[1].strip()

    if not token:
        return

    # Find chat ID from sessions
    sessions_dir = Path.home() / ".hermes" / "sessions"
    if sessions_dir.exists():
        import glob

        for sf in sorted(glob.glob(str(sessions_dir / "*.jsonl")), reverse=True):
            try:
                for line in open(sf):
                    d = json.loads(line)
                    cid = d.get("origin", {}).get("chat_id")
                    if cid:
                        chat_id = str(cid)
                        break
            except Exception:
                pass
            if chat_id:
                break

    if not chat_id:
        return

    try:
        urllib.request.urlopen(
            urllib.request.Request(
                f"https://api.telegram.org/bot{token}/sendMessage",
                data=json.dumps(
                    {
                        "chat_id": chat_id,
                        "text": f"🧠 Rook Hyperagent:\n{message}",
                        "parse_mode": "HTML",
                    }
                ).encode(),
                headers={"Content-Type": "application/json"},
            ),
            timeout=10,
        )
    except Exception:
        pass
