from __future__ import annotations

import json
import os
import sys
from datetime import datetime
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.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import login_player_sub_account_by_sms
from e2e.utils.account_store import account_store
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", "").strip()
    order_title = os.getenv("E2E_DELIVERY_ORDER_TITLE", "").strip()
    player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "19667441530").strip()
    expected_amount = os.getenv("E2E_DELIVERY_EXPECTED_PLAYER_AMOUNT", "70").strip()
    assert source_order_no, "请通过 E2E_DELIVERY_SOURCE_ORDER_NO 指定要校验收入的来源单号"
    if not order_title:
        order_title = f"E2E手工录单{source_order_no[-10:]}"

    player_account = account_store().find(phone=player_phone)
    assert player_account, f"台账中未找到打手账号：{player_phone}"

    run_dir = Path("runtime/probes/player_income_only") / (
        datetime.now().strftime("%Y%m%d-%H%M%S") + f"-{source_order_no}"
    )
    run_dir.mkdir(parents=True, exist_ok=True)

    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-INCOME-ONLY")

        login_player_sub_account_by_sms(page, settings, bug_reporter, player_account)
        player_page = WanyoujiFulfillmentPage(page, settings.tenant_home_url, bug_reporter)
        result_text = player_page.verify_player_income_for_order(
            source_order_no,
            order_title,
            expected_amount=expected_amount,
        )

        snapshot = {
            "source_order_no": source_order_no,
            "order_title": order_title,
            "player_phone": player_phone,
            "expected_amount": expected_amount,
            "result_text": result_text,
            "page_url": page.url,
            "body_text": page.locator("body").inner_text(timeout=5000),
        }
        (run_dir / "snapshot.json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
        page.screenshot(path=str(run_dir / "page.png"), full_page=True)
        print(f"打手收入校验探测完成：{run_dir}")
        context.close()
        browser.close()


if __name__ == "__main__":
    main()
