"""Test batch sender — sends ONLY to owner phone."""
import asyncio, csv, os, sys, random
from pathlib import Path
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8', errors='replace')

BASE_DIR     = Path(__file__).parent.parent
CONTACTS_CSV = BASE_DIR / 'data/processed/aima_test_contacts.csv'
LOG_CSV      = BASE_DIR / 'data/processed/aima_test_telegram_log.csv'
LEDGER_CSV   = BASE_DIR / 'data/processed/aima_telegram_message_ledger.csv'
DEFAULT_ENV  = [BASE_DIR / '.env']
DELAY_RANGE  = (3, 6)

sys.path.insert(0, str(BASE_DIR / 'src'))
from aima_telegram_log import DEFAULT_LEDGER_CSV, log_sent
from telethon import TelegramClient
from telethon.tl.functions.contacts import GetContactsRequest, ImportContactsRequest
from telethon.tl.types import InputPhoneContact

def load_env():
    for path in DEFAULT_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 normalize_phone(v):
    return ''.join(c for c in str(v or '') if c.isdigit() or c == '+')

async def resolve_recipient(client, phone, first_name, last_name):
    wanted = normalize_phone(phone).lstrip('+')
    result = await client(GetContactsRequest(hash=0))
    for user in result.users:
        up = normalize_phone(getattr(user, 'phone', '') or '').lstrip('+')
        if up and up == wanted:
            return user
    contact = InputPhoneContact(client_id=0, phone=phone,
                                first_name=first_name or phone[-4:], last_name=last_name or '')
    imported = await client(ImportContactsRequest([contact]))
    if not imported.users:
        raise RuntimeError(f'phone {phone} has no Telegram account')
    return imported.users[0]

async def run_batch():
    load_env()
    api_id   = os.environ.get('TG_API_ID')
    api_hash = os.environ.get('TG_API_HASH')
    if not api_id or not api_hash:
        raise SystemExit('TG_API_ID/TG_API_HASH missing')
    session_path = BASE_DIR / 'data/processed/telegram/aima_support_session'
    with CONTACTS_CSV.open(encoding='utf-8-sig') as f:
        queue = list(csv.DictReader(f))
    print(f'[init] test queue={len(queue)}')
    client = TelegramClient(str(session_path), int(api_id), api_hash)
    await client.connect()
    if not await client.is_user_authorized():
        raise SystemExit('Session not authorized')
    me = await client.get_me()
    print(f'[auth] {getattr(me, "first_name", "")} (@{getattr(me, "username", "?")})')
    sent_ok = no_account = errors = 0
    for i, row in enumerate(queue):
        phone = normalize_phone(row['phone'])
        message = row['gate1_text']
        print(f'[{i+1}/{len(queue)}] {phone[-4:]} variant={row.get("variant","")}')
        try:
            entity = await resolve_recipient(client, phone, row.get('first_name',''), row.get('last_name',''))
        except RuntimeError as exc:
            print(f'  [skip] {exc}'); no_account += 1; continue
        try:
            await client.send_message(entity, message)
            log_sent(LOG_CSV, LEDGER_CSV, pilot_id=row['pilot_id'],
                     phone=phone, recipient_id=str(getattr(entity, 'id', '')),
                     message=message, notes='batch_send_test')
            print(f'  [sent]'); sent_ok += 1
        except Exception as exc:
            print(f'  [error] {exc}'); errors += 1
        if i < len(queue) - 1:
            d = random.uniform(*DELAY_RANGE)
            print(f'  [pause] {d:.0f}s')
            await asyncio.sleep(d)
    await client.disconnect()
    print(f'[done] sent={sent_ok} no_account={no_account} errors={errors}')

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run_batch())

if __name__ == '__main__':
    main()
