"""One-time interactive bootstrap for the Telegram Web test session.

Opens a VISIBLE chromium, waits for the USER to log in to web.telegram.org
(QR code or phone number — you do this yourself, the script never enters
credentials), then saves the Playwright storage_state to the session path.

Run on a machine with display access:
    python bootstrap_session.py
    # optional: TG_PROXY_URL=http://127.0.0.1:2081 python bootstrap_session.py

The session is a live login — it lives in ~/.gaechkin/ (outside any repo) and
must never be committed. Copy to the mini afterwards if bootstrapped locally:
    scp ~/.gaechkin/tg_test_session.json cebers_mini@Cebers-mini.local:~/.gaechkin/
"""
from __future__ import annotations

import asyncio
import os
from pathlib import Path

from playwright.async_api import async_playwright

SESSION_FILE = Path(os.path.expanduser("~/.gaechkin/tg_test_session.json"))
TG_WEB_URL = "https://web.telegram.org/k/"


async def main() -> None:
    SESSION_FILE.parent.mkdir(parents=True, exist_ok=True)
    proxy_url = os.getenv("TG_PROXY_URL")
    launch_kwargs: dict = {"headless": False}
    if proxy_url:
        launch_kwargs["proxy"] = {"server": proxy_url}

    async with async_playwright() as pw:
        browser = await pw.chromium.launch(**launch_kwargs)
        # Reuse an existing session as a starting point if present.
        ctx_kwargs: dict = {
            "locale": "ru-RU",
            "viewport": {"width": 1280, "height": 800},
        }
        if SESSION_FILE.exists():
            ctx_kwargs["storage_state"] = str(SESSION_FILE)
        ctx = await browser.new_context(**ctx_kwargs)
        page = await ctx.new_page()
        await page.goto(TG_WEB_URL, wait_until="domcontentloaded", timeout=60_000)

        print("=" * 64)
        print("Telegram Web opened in a browser window.")
        print("1. Log in (scan the QR with your phone, or enter your number).")
        print("2. Open any chat so the app is fully initialised.")
        print("3. Come back here and press Enter to save the session.")
        print("=" * 64)
        # blocking input in a thread so the event loop keeps the browser alive
        await asyncio.get_event_loop().run_in_executor(None, input, "Press Enter when logged in... ")

        await ctx.storage_state(path=str(SESSION_FILE))
        print(f"Saved session → {SESSION_FILE}")
        await ctx.close()


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