"""Telegram CLI commands — setup and configuration."""

import os

import httpx
import typer

from fliiq.cli import display

telegram_app = typer.Typer(help="Telegram bot setup and management")

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


@telegram_app.command("setup")
def setup():
    """Set up Telegram by detecting your chat ID automatically."""
    bot_token = os.environ.get("TELEGRAM_BOT_TOKEN")
    if not bot_token:
        display.print_error(
            "TELEGRAM_BOT_TOKEN not set. Add it to your .env file first.\n"
            "Get a token from @BotFather on Telegram."
        )
        raise typer.Exit(1)

    typer.echo("Send any message to your Fliiq Telegram bot, then press Enter here...")
    try:
        input()
    except (KeyboardInterrupt, EOFError):
        typer.echo("\nCancelled.")
        raise typer.Exit(0)

    # Poll getUpdates for the most recent message
    try:
        resp = httpx.get(
            f"{TELEGRAM_API_BASE}/bot{bot_token}/getUpdates",
            params={"limit": 5, "timeout": 0},
            timeout=15,
        )
    except httpx.HTTPError as e:
        display.print_error(f"Failed to reach Telegram API: {e}")
        raise typer.Exit(1)

    if resp.status_code != 200:
        display.print_error(f"Telegram API error ({resp.status_code}): {resp.text[:200]}")
        raise typer.Exit(1)

    updates = resp.json().get("result", [])
    if not updates:
        display.print_error(
            "No messages found. Make sure you sent a message to the bot and try again."
        )
        raise typer.Exit(1)

    # Use the most recent message
    latest = updates[-1]
    msg = latest.get("message", {})
    chat = msg.get("chat", {})
    chat_id = chat.get("id")
    username = chat.get("username", "")
    first_name = chat.get("first_name", "")

    if not chat_id:
        display.print_error("Could not extract chat ID from the message. Try again.")
        raise typer.Exit(1)

    display_name = f"@{username}" if username else first_name or str(chat_id)
    typer.echo(f"Found Telegram user {display_name} (chat ID: {chat_id})")

    # Update .env file
    _update_env_allowed_ids(chat_id)

    typer.echo("Done! Your Telegram chat ID has been added to the allowed list.")
    typer.echo("Restart the daemon for changes to take effect: fliiq daemon restart")


def _update_env_allowed_ids(new_chat_id: int) -> None:
    """Add a chat ID to TELEGRAM_ALLOWED_CHAT_IDS in the active .env file."""
    from fliiq.runtime.config import resolve_env_file

    env_path = resolve_env_file()
    if not env_path:
        display.print_error("No .env file found. Run `fliiq init` first.")
        raise typer.Exit(1)

    content = env_path.read_text()
    lines = content.splitlines()

    # Find existing TELEGRAM_ALLOWED_CHAT_IDS line
    found_idx = None
    for i, line in enumerate(lines):
        stripped = line.strip()
        if stripped.startswith("TELEGRAM_ALLOWED_CHAT_IDS="):
            found_idx = i
            break

    if found_idx is not None:
        # Parse existing value
        existing = lines[found_idx].split("=", 1)[1].strip()
        existing_ids = {s.strip() for s in existing.split(",") if s.strip()}

        if str(new_chat_id) in existing_ids:
            typer.echo(f"Chat ID {new_chat_id} is already in the allowed list.")
            return

        # Ask if they want to add or replace
        if existing_ids:
            add = typer.confirm(
                f"Existing allowed IDs: {', '.join(existing_ids)}. Add {new_chat_id} to the list?",
                default=True,
            )
            if add:
                existing_ids.add(str(new_chat_id))
            else:
                existing_ids = {str(new_chat_id)}

        lines[found_idx] = f"TELEGRAM_ALLOWED_CHAT_IDS={','.join(existing_ids)}"
    else:
        lines.append(f"TELEGRAM_ALLOWED_CHAT_IDS={new_chat_id}")

    env_path.write_text("\n".join(lines) + "\n")
    typer.echo(f"Updated {env_path}")
