
import asyncio, csv, json, os, sys, sqlite3
from pathlib import Path

BASE_DIR = Path("/var/www/vps2.happyuser.info/AIMA_bot")
TG_SESSION = BASE_DIR / "data/processed/telegram/aima_support_session"

def load_env():
    for path in [BASE_DIR / ".env"]:
        if not path.exists(): continue
        for raw in path.read_text(encoding="utf-8", errors="ignore").splitlines():
            line = raw.strip()
            if not line or line.startswith("#") or "=" not in line: continue
            k, v = line.split("=", 1)
            os.environ.setdefault(k.strip(), v.strip().strip('"').strip("'"))

async def test():
    load_env()
    api_id   = os.environ.get("TG_API_ID")
    api_hash = os.environ.get("TG_API_HASH")
    from telethon import TelegramClient
    from telethon.tl.functions.contacts import ImportContactsRequest
    from telethon.tl.types import InputPhoneContact

    client = TelegramClient(str(TG_SESSION), int(api_id), api_hash)
    print("[1] connecting...", flush=True)
    await client.connect()
    print("[1] authorized:", await client.is_user_authorized(), flush=True)

    # Читаємо 5 контактів з ПОЧАТКУ датасету (row_index ASC)
    conn = sqlite3.connect(str(BASE_DIR/"data/processed/aima_conversion_shadow.sqlite"))
    cur  = conn.cursor()
    sql1 = "SELECT lead_id, first_name, last_name, phone, registered_at FROM aima_imported_contacts WHERE dataset='users_without_shop_202605191510' ORDER BY row_index ASC LIMIT 20"
    cur.execute(sql1)
    rows = cur.fetchall()
    conn.close()
    print(f"[2] Перші 20 (row_index ASC): {[r[3] for r in rows]}", flush=True)

    # Тест 1: ImportContactsRequest(5 з початку)
    print("[3] ImportContactsRequest(5 з початку)...", flush=True)
    import time as t
    start = t.time()
    req = [InputPhoneContact(client_id=i+1, phone=r[3],
           first_name=r[1] or r[3][-4:], last_name=r[2] or "")
           for i,r in enumerate(rows[:5])]
    result = await client(ImportContactsRequest(req))
    elapsed = t.time() - start
    print(f"  users={len(result.users)} retry={len(getattr(result,'retry_contacts',[]))} elapsed={elapsed:.1f}s", flush=True)
    for u in result.users:
        print(f"  found: {getattr(u,'phone','')} {getattr(u,'first_name','')}", flush=True)

    # Тест 2: ImportContactsRequest(5 з кінця)
    print("[4] Читаємо 5 з кінця (row_index DESC)...", flush=True)
    conn = sqlite3.connect(str(BASE_DIR/"data/processed/aima_conversion_shadow.sqlite"))
    cur  = conn.cursor()
    sql2 = "SELECT lead_id, first_name, last_name, phone, registered_at FROM aima_imported_contacts WHERE dataset='users_without_shop_202605191510' ORDER BY row_index DESC LIMIT 5"
    cur.execute(sql2)
    rows_end = cur.fetchall()
    conn.close()
    req2 = [InputPhoneContact(client_id=i+10, phone=r[3],
            first_name=r[1] or r[3][-4:], last_name=r[2] or "")
            for i,r in enumerate(rows_end)]
    start = t.time()
    result2 = await client(ImportContactsRequest(req2))
    elapsed2 = t.time() - start
    print(f"  users={len(result2.users)} retry={len(getattr(result2,'retry_contacts',[]))} elapsed={elapsed2:.1f}s", flush=True)

    await client.disconnect()
    print("[done]", flush=True)

asyncio.get_event_loop().run_until_complete(test())
