"""Minimal Telethon connection test — run on server to verify session works."""
import sys, os, asyncio
from pathlib import Path

BASE = Path(__file__).parent
sys.stdout.reconfigure(line_buffering=True)

for p in [BASE / ".env"]:
    if p.exists():
        for line in p.read_text(errors="ignore").splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                k, v = line.split("=", 1)
                os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))

api_id = os.environ.get("TG_API_ID")
api_hash = os.environ.get("TG_API_HASH")
session = str(BASE / "data/processed/telegram/aima_support_session")
print(f"api_id={api_id}, session={session}")

from telethon import TelegramClient
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPhoneContact

async def run():
    c = TelegramClient(session, int(api_id), api_hash)
    print("connecting...")
    await c.connect()
    auth = await c.is_user_authorized()
    print(f"authorized={auth}")
    if not auth:
        print("NOT AUTHORIZED"); return
    me = await c.get_me()
    print(f"me={me.first_name} {me.last_name}, premium={getattr(me, 'premium', False)}")

    # Test ImportContactsRequest with 1 dummy contact
    test = [InputPhoneContact(client_id=1, phone="+380000000001",
                              first_name="Test", last_name="")]
    r = await c(ImportContactsRequest(test))
    print(f"ImportContacts test: users={len(r.users)}, retry={len(getattr(r,'retry_contacts',[]))}")

    await c.disconnect()
    print("DONE")

asyncio.run(run())
