from __future__ import annotations

import time

from loguru import logger

from flow_xhs.platform import REDNOTE_PLATFORM
from flow_xhs.runtime.enums import Platform
from flow_xhs.runtime.accounts.manager import AccountManager
from flow_xhs.runtime.browser.manager import browser_manager, stealth_async
from flow_xhs.runtime.database.manager import DatabaseManager
from flow_xhs.platform.factory import PlatformFactory
from flow_xhs.services.account_list import execute_account_list
from flow_xhs.errors import InvalidArgsError


async def _refresh_account_status(account: dict, *, platform_enum: Platform) -> None:
    user_no = str(account.get("user_no") or "").strip()
    if not user_no:
        return

    is_logged_in = False
    nickname = account.get("nickname")
    refreshed_state = account.get("storage_state")
    check_time = int(time.time())
    profile = AccountManager.get_login_profile(platform_enum)

    try:
        async with browser_manager.get_context(
            storage_state=account.get("storage_state"),
            account_key=user_no,
        ) as context:
            page = await context.new_page()
            await stealth_async(page)
            extractor = PlatformFactory.get_extractor(platform_enum, page)

            await page.goto(profile.login_url, wait_until="domcontentloaded")
            await page.wait_for_timeout(500)
            has_logged_in_selector = await page.locator(profile.login_selector).count() > 0
            is_logged_in = has_logged_in_selector

            if has_logged_in_selector:
                try:
                    info = await extractor.get_self_info()
                    if isinstance(info, dict):
                        info_nickname = str(info.get(profile.nickname_field) or "").strip()
                        if info_nickname:
                            nickname = info_nickname
                        self_uid = str(info.get(profile.account_id_field) or "").strip()
                        if self_uid and self_uid != user_no:
                            # Cookie 已漂移到其他账号，当前账号视为失效。
                            is_logged_in = False
                        elif profile.guest_field in info:
                            is_logged_in = not bool(info.get(profile.guest_field))
                except Exception as exc:
                    logger.warning(f"Self info check failed for account {user_no}: {exc}")

            refreshed_state = await context.storage_state()
    except Exception as exc:
        logger.warning(f"Account status probe failed for account {user_no}: {exc}")

    DatabaseManager.upsert_account(
        {
            "platform": account.get("platform"),
            "user_no": user_no,
            "nickname": nickname,
            "is_logged_in": bool(is_logged_in),
            "check_time": check_time,
            "usage_time": account.get("usage_time"),
            "storage_state": refreshed_state,
        }
    )


def _load_platform_accounts() -> list[dict]:
    accounts = DatabaseManager.get_all_accounts(only_active=False)
    return [acc for acc in accounts if acc.get("platform") == REDNOTE_PLATFORM]


async def execute_auth_status(account_uid: str | None = None) -> list[dict]:
    platform_enum = Platform(REDNOTE_PLATFORM)
    platform_accounts = _load_platform_accounts()

    if account_uid:
        target = str(account_uid).strip()
        account = next((acc for acc in platform_accounts if str(acc.get("user_no") or "").strip() == target), None)
        if not account:
            raise InvalidArgsError(f"账号不存在: {target}")
        accounts_to_probe = [account]
    else:
        accounts_to_probe = [acc for acc in platform_accounts if bool(acc.get("is_logged_in"))]

    for account in accounts_to_probe:
        await _refresh_account_status(account, platform_enum=platform_enum)

    return execute_account_list(only_active=False)
