#!/usr/bin/env python3
"""One-time interactive Telegram login — run this by hand, once, before the first
scheduled digest run.

    docker compose run --rm --entrypoint python digest-engine ingest/telegram_login.py

It prompts for the phone number, the code Telegram sends, and the 2FA password if
the account has one, then writes the session to TELEGRAM_SESSION_PATH (a mounted
volume, so it survives `--rm`). telegram_ingest.py reuses that session
non-interactively from then on.

Get TELEGRAM_API_ID / TELEGRAM_API_HASH from https://my.telegram.org -> API
development tools.
"""

import os
import sys

from telethon import TelegramClient

DEFAULT_SESSION_PATH = "/data/telegram.session"


def main():
    api_id = os.environ.get("TELEGRAM_API_ID", "").strip()
    api_hash = os.environ.get("TELEGRAM_API_HASH", "").strip()
    session_path = os.environ.get("TELEGRAM_SESSION_PATH", DEFAULT_SESSION_PATH)

    if not (api_id and api_hash):
        print("TELEGRAM_API_ID and TELEGRAM_API_HASH must be set (see digest-engine.env.example).", file=sys.stderr)
        return 1

    print(f"Creating Telegram session at {session_path}")
    with TelegramClient(session_path, int(api_id), api_hash) as client:
        me = client.get_me()
        print(f"Logged in as {me.username or me.first_name} (id {me.id}).")

    print("Done. telegram_ingest.py will reuse this session non-interactively.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
