from __future__ import annotations

from typing import Callable

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.errors import CliTimeoutError, InternalError, InvalidArgsError


async def execute_auth_login(
    *,
    mode: str = "local",
    login_timeout_seconds: int = 240,
    screenshot_path: str = "",
    account_uid: str = "",
    progress_callback: Callable[[dict], None] | None = None,
) -> dict:
    normalized_mode = mode.strip().lower()
    if normalized_mode not in {"local", "remote"}:
        raise InvalidArgsError("`--mode` 仅支持 local 或 remote")

    platform_enum = Platform(REDNOTE_PLATFORM)
    result = await AccountManager.login_and_add_account(
        platform_enum,
        mode=normalized_mode,
        timeout_seconds=login_timeout_seconds,
        screenshot_path=screenshot_path,
        account_uid=account_uid,
        progress_callback=progress_callback,
    )
    if result.get("success"):
        return {"platform": platform_enum.value, **result}

    reason = result.get("reason")
    message = result.get("message") or "登录失败"
    details = {
        "mode": normalized_mode,
        "account_uid": account_uid or None,
        "reason": reason,
        "screenshot_path": result.get("screenshot_path"),
    }
    if isinstance(result.get("details"), dict):
        details.update(result["details"])
    if reason == "login_timeout":
        raise CliTimeoutError(
            message=message,
            details={**details, "timeout_seconds": login_timeout_seconds},
        )
    if reason in {"account_not_found", "account_mismatch"}:
        raise InvalidArgsError(
            message=message,
            details=details,
        )
    raise InternalError(
        message=message,
        details=details,
    )
