#!/usr/bin/env python3
"""Discover chat IDs the bot can currently see via getUpdates.

Run once after adding the bot to all Mars chats. Copy the printed
chat_id values into chats.json under the chosen aliases.
"""
import sys
from pathlib import Path

# Allow running without install: prepend src/ to path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "src"))

import requests
from mars_bot.config import load_config, ConfigError


def main() -> int:
    try:
        cfg = load_config(ROOT)
    except ConfigError as e:
        print(f"Config error: {e}", file=sys.stderr)
        return 1

    url = f"https://api.telegram.org/bot{cfg.bot_token}/getUpdates"
    try:
        resp = requests.get(url, timeout=15)
        data = resp.json()
    except Exception as e:
        print(f"Bot API call failed: {e}", file=sys.stderr)
        return 1

    if not data.get("ok"):
        print(f"Bot API error: {data}", file=sys.stderr)
        return 1

    seen = {}
    for update in data.get("result", []):
        msg = (
            update.get("message")
            or update.get("channel_post")
            or update.get("edited_message")
            or update.get("edited_channel_post")
        )
        if not msg or "chat" not in msg:
            continue
        chat = msg["chat"]
        chat_id = chat["id"]
        title = (
            chat.get("title")
            or chat.get("username")
            or chat.get("first_name")
            or "Unknown"
        )
        seen[chat_id] = title

    if not seen:
        print("No chats found in getUpdates response.")
        print("Troubleshooting:")
        print("  - did the bot receive any message AFTER being added to the chats?")
        print("    (in groups: mention the bot or send /start@<botname>)")
        print("  - is a webhook configured? clear it:")
        print(f"      curl https://api.telegram.org/bot<TOKEN>/deleteWebhook")
        print("  - for groups: check privacy mode at @BotFather → /mybots → bot →")
        print("    Bot Settings → Group Privacy → Turn off, then re-trigger a message")
        return 2

    print("Discovered chats:")
    for cid, title in sorted(seen.items()):
        print(f"  {title!r:40s}  →  {cid}")
    print()
    print("Copy these chat_id values into chats.json under aliases of your choice.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
