#!/usr/bin/env python3
"""[zemlya-report-e2e] Скриншоты цикла отчёта (запускать на mini: /usr/bin/python3).

ENV:
  ZW_TOKEN  — admin zw_session (issue(1005954706,3))
  FREE_ID   — id free-отчёта (опц.)
  AI_ID     — id ai-отчёта (опц.)
  ZW_OUT    — каталог PNG (default /tmp/zw_e2e_shots)
  ZW_BASE   — base url (default http://127.0.0.1:20141)
Кладёт PNG в ZW_OUT и печатает текстовые маркеры новых блоков.
"""
import asyncio, os
from playwright.async_api import async_playwright

TOKEN = os.environ["ZW_TOKEN"]
FREE = os.environ.get("FREE_ID")
AI = os.environ.get("AI_ID")
BASE = os.environ.get("ZW_BASE", "http://127.0.0.1:20141")
OUT = os.environ.get("ZW_OUT", "/tmp/zw_e2e_shots")
UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")
# маркеры новых/важных блоков отчёта — расширяй при добавлении фич
MARKERS = ["Границы участка", "межевани", "Негативн", "кладбищ", "Свалк", "полигон",
           "Промзона", "очистны", "До ближайшего города", "До города",
           "Локация и транспорт", "Экология", "Форма права"]


async def main():
    os.makedirs(OUT, exist_ok=True)
    async with async_playwright() as p:
        b = await p.chromium.launch(headless=True)
        ctx = await b.new_context(viewport={"width": 1280, "height": 1000}, user_agent=UA)
        ck = {"value": TOKEN, "path": "/", "httpOnly": True, "secure": False, "sameSite": "Lax"}
        await ctx.add_cookies([{"name": "zw_session", "domain": "127.0.0.1", **ck},
                               {"name": "zw_session", "domain": "localhost", **ck}])

        async def shot(path, name, wait=2000):
            pg = await ctx.new_page()
            try:
                await pg.goto(BASE + path, wait_until="networkidle", timeout=60000)
            except Exception as e:
                print("goto warn", path, repr(e)[:100])
            await pg.wait_for_timeout(wait)
            await pg.screenshot(path=f"{OUT}/{name}.png", full_page=True)
            try:
                txt = await pg.inner_text("body")
            except Exception:
                txt = ""
            print(f"=== {name} url={pg.url} len={len(txt)}")
            for kw in MARKERS:
                if kw.lower() in (txt or "").lower():
                    print(f"     marker[{name}]: {kw}")
            await pg.close()

        await shot("/dashboard", "01_dashboard")
        await shot("/dashboard/new", "02_new_form")
        if FREE:
            await shot(f"/reports/{FREE}", "03_free_report", wait=2500)
        if AI:
            await shot(f"/reports/{AI}", "04_ai_report", wait=4000)
            await shot(f"/api/reports/{AI}/ai-html", "05_ai_html_raw", wait=2500)
        await b.close()

asyncio.run(main())
