from __future__ import annotations

import os
import sys
from pathlib import Path

from playwright.sync_api import sync_playwright

sys.path.insert(0, os.getcwd())

from e2e.conftest import settings as settings_fixture
from e2e.pages.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.utils.bug_reporter import BugReporter


def main() -> None:
    sys.stdout.reconfigure(encoding="utf-8")
    settings = settings_fixture.__wrapped__()
    source_order_no = os.getenv("E2E_DELIVERY_SOURCE_ORDER_NO", "E2EORDER0609120015")
    order_title = os.getenv("E2E_DELIVERY_ORDER_TITLE", f"E2E手工录单{source_order_no[-10:]}")
    owner_phone = os.getenv("E2E_TASK_WANYOUJI_PHONE", "19844527868")
    owner_password = os.getenv("E2E_TASK_WANYOUJI_PASSWORD", "test123456")

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(viewport={"width": settings.viewport_width, "height": settings.viewport_height})
        page = context.new_page()
        bug_reporter = BugReporter(page, case_id="E2E-DELIVERY-002-OBSERVE")
        owner_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)

        owner_page.login_main_account(owner_phone, owner_password)
        frame = owner_page.open_workshop_order_list()
        text = owner_page.search_workshop_order_list(frame, source_order_no, order_title)
        assert source_order_no in text or order_title in text, (
            f"未找到订单；source_order_no={source_order_no}; order_title={order_title}; text={text[:1500]}"
        )
        clicked = owner_page.click_workshop_order_list_action(frame, source_order_no, "操作")
        assert clicked, f"未点开主单操作弹窗；source_order_no={source_order_no}"
        print("已打开主单操作弹窗。请手动操作；完成后回到对话告诉我“好了”。")

        marker = Path("runtime/manual_observe_done.txt")
        marker.parent.mkdir(parents=True, exist_ok=True)
        marker.write_text("", encoding="utf-8")
        print(f"如需让脚本自动结束，可写入任意内容到：{marker.resolve()}")
        while not marker.read_text(encoding="utf-8").strip():
            page.wait_for_timeout(1000)

        context.close()
        browser.close()


if __name__ == "__main__":
    main()
