"""Live-тест KF3: PDF-резюме → автозаполнение профиля."""
import asyncio
import sys
import time
from pathlib import Path

SESSION = "/Users/cebers_mini/.gaechkin/tg_test_session.json"
SHOTS = Path("/tmp/vh_audit/shots_kf3")
SHOTS.mkdir(parents=True, exist_ok=True)
PROXY = "http://127.0.0.1:2081"
BOT = "VakHunter_bot"
PDF = "/tmp/resume_test.pdf"
RES = []


def add(name, ok, detail=""):
    RES.append(ok)
    print((("✅" if ok else "❌") + f" {name}: {detail}")[:180], flush=True)


async def shoot(page, name):
    try:
        await page.screenshot(path=str(SHOTS / f"{int(time.time())}_{name}.png"))
    except Exception:
        pass


async def last_text(page, n=2):
    bubbles = await page.locator(".bubble.is-in .message").all()
    out = []
    for b in bubbles[-n:]:
        try:
            out.append(await b.inner_text())
        except Exception:
            pass
    return "\n||\n".join(out)


async def wait_text(page, markers, timeout_s=60, n=2):
    deadline = time.time() + timeout_s
    txt = ""
    while time.time() < deadline:
        txt = await last_text(page, n)
        if any(m in txt for m in markers):
            return txt
        await page.wait_for_timeout(2500)
    return txt


async def main():
    from playwright.async_api import async_playwright
    async with async_playwright() as pw:
        browser = await pw.chromium.launch(headless=True, proxy={"server": PROXY})
        ctx = await browser.new_context(storage_state=SESSION,
                                        viewport={"width": 1280, "height": 1100},
                                        locale="ru-RU")
        page = await ctx.new_page()
        try:
            await page.goto(f"https://web.telegram.org/k/#@{BOT}",
                            wait_until="domcontentloaded", timeout=60000)
            await page.wait_for_timeout(7000)

            # сперва входим в режим загрузки резюме: Профиль → Загрузить резюме
            inp = page.locator(".input-message-input").first
            await inp.click()
            await inp.fill("👤 Профиль")
            await page.wait_for_timeout(800)
            send_btn = page.locator(".btn-send")
            if await send_btn.count():
                await send_btn.first.click()
            else:
                await page.keyboard.press("Enter")
            await page.wait_for_timeout(4000)
            up_btn = page.locator('.bubble.is-in .reply-markup-button:has-text("Загрузить резюме")')
            add("кнопка «Загрузить резюме» в профиле", await up_btn.count() >= 1)
            await up_btn.last.click()
            await page.wait_for_timeout(3000)
            await shoot(page, "00_upload_mode")

            # загрузка файла: скрепка → пункт «Document» → file chooser
            attach = page.locator(".attach-file, .btn-icon.attach-file, .new-message-wrapper .btn-icon").first
            await attach.click()
            await page.wait_for_timeout(1500)
            await shoot(page, "00_attach_menu")
            doc_item = page.locator('.btn-menu-item:has-text("Document"), .btn-menu-item:has-text("Документ"), .btn-menu-item:has-text("файл")')
            n_menu = await doc_item.count()
            add("меню аттача открыто", n_menu >= 1, f"items={n_menu}")
            async with page.expect_file_chooser(timeout=10000) as fc_info:
                await doc_item.first.click()
            fc = await fc_info.value
            await fc.set_files(PDF)
            await page.wait_for_timeout(3000)
            await shoot(page, "01_attach_popup")

            # попап отправки: кнопка SEND / ОТПРАВИТЬ
            sent = False
            for sel in ('.popup button:has-text("SEND")',
                        '.popup button:has-text("ОТПРАВИТЬ")',
                        '.popup .btn-primary',
                        '.popup-send'):
                btn = page.locator(sel)
                if await btn.count():
                    await btn.first.click()
                    sent = True
                    break
            if not sent:
                await page.keyboard.press("Enter")
            await page.wait_for_timeout(2000)
            await shoot(page, "02_sent")

            txt = await wait_text(page, ("Java", "профил", "Специальность", "Не удалось"),
                                  timeout_s=90)
            await shoot(page, "03_parsed")
            ok_parse = ("Java" in txt or "профил" in txt.lower()) and "Не удалось" not in txt
            add("KF3: бот разобрал резюме", ok_parse, txt[:130].replace("\n", " "))
        finally:
            await browser.close()

    print(f"\nKF3 probe: {sum(RES)}/{len(RES)} PASS")
    return 0 if all(RES) else 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))
