"""
QQ Browser Windows installer.

从官方下载服务器下载 QQ Browser 的 Windows 安装包，
使用静默安装参数进行安装。
"""

import logging
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

logger = logging.getLogger(__name__)

from .installer_common import (
    _setup_install_logging,
    _teardown_install_logging,
    _log_and_print,
    _run,
    _download_with_urllib,
)
from .constants import BROWSER_EXECUTABLE

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

BASE_URL = "https://dldir1v6.qq.com/invc/tt/QB/Public"
QB_EXE = "QQBrowserSetup.exe"


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _check_platform():
    """确保当前运行在 Windows 平台上。"""
    if sys.platform != "win32":
        _log_and_print(f"❌ Unsupported platform: {sys.platform}. This installer is for Windows only.", logging.ERROR)
        sys.exit(1)


def is_installed() -> bool:
    """检查 QQ Browser 是否已安装。

    通过检查默认安装路径和注册表来判断。
    """
    # 方式 1：检查默认可执行文件路径
    if os.path.isfile(BROWSER_EXECUTABLE):
        return True

    # 方式 2：在 PATH 中查找
    if shutil.which("QQBrowser.exe") is not None:
        return True

    # 方式 3：检查常见安装路径
    common_paths = [
        os.path.join(os.environ.get("LOCALAPPDATA", ""), "QQBrowser", "QQBrowser.exe"),
        os.path.join(os.environ.get("PROGRAMFILES", ""), "QQBrowser", "QQBrowser.exe"),
        os.path.join(os.environ.get("PROGRAMFILES(X86)", ""), "QQBrowser", "QQBrowser.exe"),
    ]
    return any(os.path.isfile(p) for p in common_paths if p)


# ---------------------------------------------------------------------------
# Install logic
# ---------------------------------------------------------------------------

def _install_exe(tmp_dir: Path):
    """下载并静默安装 QQ Browser（Windows）。"""
    pkg_path = tmp_dir / QB_EXE
    url = f"{BASE_URL}/{QB_EXE}"

    _log_and_print(f"📦 Downloading Windows installer: {QB_EXE}")
    _download_with_urllib(url, pkg_path)

    _log_and_print("📦 Installing QQ Browser (silent mode)...")
    # 使用 /S 进行静默安装（NSIS 标准参数）
    # 不同安装包可能使用不同的静默参数，常见的有 /S、/silent、/quiet
    result = _run(
        [str(pkg_path), "/S"],
        check=False,
    )
    if result.returncode != 0:
        logger.warning("Installer returned code %d, trying alternative silent flags...", result.returncode)
        # 尝试备选静默参数
        _run(
            [str(pkg_path), "/silent", "/norestart"],
            check=False,
        )


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def install(dry_run: bool = False, log_dir: str | None = None, force: bool = False) -> bool:
    """安装 QQ Browser（Windows 版）。

    Args:
        dry_run: 如果为 True，仅打印将要执行的操作，不实际安装。
        log_dir: 日志目录。
        force: 如果为 True，即使已安装也强制重新安装。

    Returns:
        True 表示安装后 QQ Browser 可用。
    """
    from .constants import DEFAULT_LOG_DIR
    if log_dir is None:
        log_dir = DEFAULT_LOG_DIR

    _setup_install_logging(log_dir)

    try:
        return _install_inner(dry_run, force=force)
    finally:
        _teardown_install_logging()


def _install_inner(dry_run: bool, force: bool = False) -> bool:
    """核心安装逻辑。"""
    _check_platform()

    # 检查是否已安装（force 模式下跳过检查，强制重装）
    if not force and is_installed():
        _log_and_print(f"✅ QQ Browser already installed: {BROWSER_EXECUTABLE}, skipping...")
        return True

    if force and is_installed():
        _log_and_print(f"🔄 QQ Browser already installed: {BROWSER_EXECUTABLE}, force reinstalling...")

    if dry_run:
        _log_and_print(f"🔍 [dry-run] Would download: {BASE_URL}/{QB_EXE}")
        _log_and_print("🔍 [dry-run] Would install via: silent exe installer")
        return True

    # 在临时目录中下载并安装
    tmp_dir = Path(tempfile.mkdtemp(prefix="qqbrowser-install-"))
    try:
        _install_exe(tmp_dir)
    except subprocess.CalledProcessError as exc:
        _log_and_print(f"❌ Installation command failed (exit code {exc.returncode}).", logging.ERROR)
        logger.error("Install failed: %s", exc)
        return False
    except Exception as exc:
        _log_and_print(f"❌ Installation failed: {exc}", logging.ERROR)
        logger.error("Install failed: %s", exc)
        return False
    finally:
        # 清理临时目录
        shutil.rmtree(tmp_dir, ignore_errors=True)

    # 验证安装结果
    if not is_installed():
        _log_and_print("❌ QQ Browser installation failed: executable not found.", logging.ERROR)
        _log_and_print("   Please try installing QQ Browser manually from https://browser.qq.com/", logging.ERROR)
        return False

    _log_and_print(f"✅ QQ Browser installed successfully: {BROWSER_EXECUTABLE}")
    return True
