#!/usr/bin/env python3
"""
Telegram MTProto login script for first-time authentication.
Bypasses mcp-telegram's pydantic-settings env_file conflict.

Usage (user must run interactively via SSH):
    bash /tmp/tg_login.sh

The script will:
1. Ask for phone number
2. Send verification code to Telegram
3. Prompt for code (type immediately when received)
4. Handle 2FA if needed
5. Save session for mcp-telegram to use
"""
import asyncio
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
import socks
import sys
import os

# === Configuration ===
# Update these or read from env
API_ID = int(os.environ.get('TG_API_ID', '0'))
API_HASH = os.environ.get('TG_API_HASH', '')
SESSION_PATH = os.path.expanduser('~/.local/share/state/mcp-telegram/mcp_telegram_session')
PROXY = (socks.SOCKS5, '127.0.0.1', 7890)  # Mihomo


async def main():
    if not API_ID or not API_HASH:
        print("Error: Set TG_API_ID and TG_API_HASH environment variables first.")
        print("  export TG_API_ID=your_id")
        print("  export TG_API_HASH=your_hash")
        sys.exit(1)

    phone = input("Phone number (with country code, e.g. +1234567890): ").strip()

    # Ensure session directory exists
    os.makedirs(os.path.dirname(SESSION_PATH), exist_ok=True)

    client = TelegramClient(SESSION_PATH, API_ID, API_HASH, proxy=PROXY)

    try:
        await client.start(phone=phone)
    except SessionPasswordNeededError:
        pwd = input("2FA password: ").strip()
        await client.sign_in(password=pwd)

    me = await client.get_me()
    print(f"\n✅ Login successful!")
    print(f"   User: {me.username} (ID: {me.id})")
    print(f"   Session saved to: {SESSION_PATH}")
    print(f"\nYou can now use mcp-telegram MCP server.")
    await client.disconnect()


if __name__ == '__main__':
    asyncio.run(main())
