from __future__ import annotations

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.wanzhanggui_order_page import ManualOrderData, WanzhangguiOrderPage


def main() -> None:
    load_dotenv()
    out_dir = Path("runtime/order_probe/service_project")
    out_dir.mkdir(parents=True, exist_ok=True)
    responses: list[str] = []

    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False, slow_mo=200, args=["--window-size=1920,1080"])
        context = browser.new_context(viewport={"width": 1920, "height": 1080}, screen={"width": 1920, "height": 1080})
        page = context.new_page()

        def collect_response(response) -> None:
            request = response.request
            if request.resource_type not in {"xhr", "fetch"}:
                return
            if "game" not in response.url.lower() and "project" not in response.url.lower() and "order" not in response.url.lower():
                return
            body = ""
            try:
                body = response.text()[:3000]
            except Exception as exc:
                body = f"<response body read failed: {exc}>"
            responses.append(
                "\n".join(
                    [
                        f"{response.status} {request.method} {response.url}",
                        f"request={request.post_data or ''}",
                        f"response={body}",
                    ]
                )
            )

        page.on("response", collect_response)
        order_page = WanzhangguiOrderPage(page, "https://test-lianlianyun.lianlianwz.com/home")
        order_page.login_main_account("19147509308", "test123456")
        frame = order_page.open_order_management()
        order_page.click_frame_button(frame, "手工录单")
        page.wait_for_timeout(2000)
        order = ManualOrderData(
            source_order_no="E2EPROBE",
            order_title="E2E服务项目探测",
            strategy_name="E2E推单策略0604153643",
            strategy_type="单平台指定",
        )
        order_page.fill_ai_order_content(frame, order.ai_text)
        page.wait_for_timeout(2000)

        service_status = order_page.select_game_service_project_by_row_position(frame)
        (out_dir / "service_status.txt").write_text(str(service_status), encoding="utf-8")
        (out_dir / "modal_text.txt").write_text(frame.locator("body").inner_text(timeout=5000), encoding="utf-8")
        (out_dir / "fields.txt").write_text("\n".join(order_page.modal_field_values(frame)), encoding="utf-8")
        (out_dir / "responses.txt").write_text("\n\n".join(responses), encoding="utf-8")
        page.screenshot(path=out_dir / "page.png", full_page=True)

        page.wait_for_timeout(5000)
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
