from __future__ import annotations

import os
import sys
from pathlib import Path

from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from e2e.pages.tenant_registration_page import TenantRegistrationPage
from e2e.pages.tenant_subscription_page import TenantSubscriptionPage
from e2e.utils.bug_reporter import BugReporter
from e2e.utils.image_captcha import ImageCaptchaSolver
from e2e.utils.verification_code import VerificationCodeProvider


load_dotenv()

OUT_DIR = Path("runtime/wanzhanggui_apply_probe")


def dump(page, name: str) -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    text = page.locator("body").inner_text(timeout=5000)
    (OUT_DIR / f"{name}.txt").write_text(f"URL: {page.url}\n\n{text}", encoding="utf-8")
    page.screenshot(path=str(OUT_DIR / f"{name}.png"), full_page=True)
    print(f"[{name}] {page.url}\n{text[:2000]}")


def main() -> None:
    phone = os.getenv("E2E_PROBE_PHONE", "19147509308")
    password = os.getenv("E2E_PROBE_PASSWORD", "test123456")
    home_url = os.getenv("TENANT_HOME_URL", "https://test-lianlianyun.lianlianwz.com/home")
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=120)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        page = context.new_page()
        bug_reporter = BugReporter(page, "PROBE-WANZHANGGUI-APPLY")
        tenant_login = TenantRegistrationPage(
            page,
            home_url,
            VerificationCodeProvider(mode="manual"),
            ImageCaptchaSolver(),
            bug_reporter,
        )
        tenant = TenantSubscriptionPage(page, home_url, tenant_login, bug_reporter)
        tenant.login_certified_tenant(phone, password)
        dump(page, "after_login")
        tenant.open_subscription_page()
        dump(page, "subscription_before")
        print("[card]", tenant.solution_card_text("丸掌柜"))
        tenant.apply_wanzhanggui(phone)
        page.wait_for_timeout(3000)
        dump(page, "subscription_after_apply")
        print("[errors]", bug_reporter.frontend_errors(), bug_reporter.network_issues)
        browser.close()


if __name__ == "__main__":
    main()
