
import asyncio, json, os, sys, time as t
from pathlib import Path

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

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("'"))

def norm(v):
    return "".join(c for c in str(v or "") if c.isdigit() or c == "+")

async def screen_not_sent():
    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

    not_sent_path = BASE_DIR / "data/processed/aima_not_sent_candidates.json"
    candidates = json.loads(not_sent_path.read_text(encoding="utf-8"))
    print(f"[screen] Перевіряємо {len(candidates)} not_sent контактів", flush=True)

    client = TelegramClient(str(TG_SESSION), int(api_id), api_hash)
    await client.connect()
    if not await client.is_user_authorized():
        print("[error] Not authorized"); sys.exit(1)
    print("[ok] Connected", flush=True)

    reachable = []
    total_scanned = 0
    total_direct = 0
    total_retry = 0

    for offset in range(0, len(candidates), BATCH):
        chunk = candidates[offset:offset+BATCH]
        req = [InputPhoneContact(client_id=offset+i+1, phone=r["phone"],
               first_name=r.get("first_name","") or r["phone"][-4:],
               last_name=r.get("last_name","") or "")
               for i,r in enumerate(chunk)]
        ts = t.time()
        result = await client(ImportContactsRequest(req))
        elapsed = t.time() - ts

        found_phones = {norm(getattr(u,"phone","") or "").lstrip("+") for u in result.users}
        retry_n = len(getattr(result,"retry_contacts",[]))

        for r in chunk:
            if norm(r["phone"]).lstrip("+") in found_phones:
                reachable.append(r)

        total_scanned += len(chunk)
        total_direct += len(result.users)
        total_retry   += retry_n
        print(f"[screen] scanned={total_scanned} direct={len(result.users)} retry={retry_n} reachable={len(reachable)} t={elapsed:.1f}s", flush=True)

    await client.disconnect()
    print(f"\n[done] Досяжних: {len(reachable)} / {total_scanned} (direct={total_direct} retry_forever={total_retry})", flush=True)

    if reachable:
        out = BASE_DIR / "data/processed/aima_reachable_from_not_sent.json"
        out.write_text(json.dumps(reachable, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"[ok] Збережено -> {out.name}", flush=True)
        for r in reachable:
            print(f"  [{r['batch']}] {r['phone']} {r.get('first_name','')} pilot={r['pilot_id']}")
    else:
        print("[warn] Жодного досяжного серед not_sent контактів")

asyncio.get_event_loop().run_until_complete(screen_not_sent())
