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.wanzhanggui_order_page import WanyoujiFulfillmentPage
from e2e.tests.订单流转.test_e2e_task_001_external_order_dispatch_to_player import (
    find_player_account,
    login_player_sub_account_by_sms,
)
from e2e.utils.account_store import account_store
from e2e.utils.bug_reporter import BugReporter
from e2e.utils.dual_browser import assert_distinct_account_contexts, dual_browser_manager


TENANT_HOME_URL = "https://test-lianlianyun.lianlianwz.com/home"


class Settings:
    def __init__(self) -> None:
        self.tenant_home_url = TENANT_HOME_URL
        self.verification_code_mode = os.getenv("E2E_VERIFICATION_CODE_MODE", "feishu")
        self.verification_code_static = os.getenv("E2E_VERIFICATION_CODE_STATIC", "")
        self.manual_code_file = os.getenv("E2E_MANUAL_CODE_FILE", "runtime/sms_code.txt")
        self.manual_code_timeout_seconds = int(os.getenv("E2E_MANUAL_CODE_TIMEOUT_SECONDS", "180"))
        self.manual_code_poll_interval_seconds = int(os.getenv("E2E_MANUAL_CODE_POLL_INTERVAL_SECONDS", "2"))
        self.feishu_app_id = os.getenv("FEISHU_APP_ID", "")
        self.feishu_app_secret = os.getenv("FEISHU_APP_SECRET", "")
        self.feishu_chat_id = os.getenv("FEISHU_CHAT_ID", "")
        self.feishu_timeout_seconds = int(os.getenv("FEISHU_TIMEOUT_SECONDS", "60"))
        self.feishu_poll_interval_seconds = int(os.getenv("FEISHU_POLL_INTERVAL_SECONDS", "3"))


def resolve_accounts() -> tuple:
    store = account_store()
    source_order_no = os.getenv("E2E_S_FLOW_SOURCE_ORDER_NO", "").strip()
    explicit_wanyouji_phone = os.getenv("E2E_ORDER_WANYOUJI_PHONE", "").strip()
    explicit_player_phone = os.getenv("E2E_TASK_PLAYER_PHONE", "").strip()
    order = None
    if source_order_no:
        order = next((item for item in store.load_payload().get("dispatched_orders", []) if item.get("source_order_no") == source_order_no), None)
    wanyouji_phone = explicit_wanyouji_phone or (order or {}).get("task_wanyouji_phone") or ((order or {}).get("wanyouji_phones") or [""])[0]
    wanyouji = store.find(phone=wanyouji_phone) if wanyouji_phone else store.find_wanyouji_owner_for_member()
    assert wanyouji is not None, "未找到可用于隔离验证的丸友集主账号"
    player = find_player_account(wanyouji, explicit_player_phone)
    assert player is not None, f"丸友集账号 {wanyouji.phone} 下未找到可用打手账号"
    return wanyouji, player


def main() -> None:
    load_dotenv()
    wanyouji, player = resolve_accounts()
    settings = Settings()
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(channel="chrome", headless=False, slow_mo=150)
        context = browser.new_context(viewport={"width": 1440, "height": 900})
        seed_page = context.new_page()
        try:
            bug_reporter = BugReporter(seed_page, case_id="PROBE-WANYOUJI-PLAYER-CONTEXT")
            owner_page = WanyoujiFulfillmentPage(seed_page, settings.tenant_home_url, bug_reporter)
            owner_page.login_main_account(wanyouji.phone, wanyouji.password)
            player_page = login_player_sub_account_by_sms(owner_page.page, settings, bug_reporter, player)
            assert_distinct_account_contexts(owner_page.page, wanyouji.phone, player_page, player.phone)
            print(
                "context isolation ok: "
                f"wanyouji={wanyouji.phone} role={getattr(owner_page.page, '_e2e_dual_browser_role', '')}; "
                f"player={player.phone} role={getattr(player_page, '_e2e_dual_browser_role', '')}"
            )
        finally:
            dual_browser_manager().close()
            try:
                context.close()
            except Exception:
                pass
            browser.close()


if __name__ == "__main__":
    main()
