from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path


def portable_root_dir() -> Path:
    """返回便携包根目录；exe 位于 WaWaCloud 根目录时就是 exe 所在目录。"""
    override = os.environ.get("WAWA_PORTABLE_ROOT", "").strip()
    if override:
        return Path(override)
    if getattr(sys, "frozen", False):
        return Path(sys.executable).resolve().parent
    source_override = os.environ.get("WAWA_HOT_UPDATE_SOURCE_DIR", "").strip()
    if source_override:
        source_dir = Path(source_override).resolve()
        if source_dir.name.lower() == "source":
            return source_dir.parent
    return Path.cwd()


def ensure_portable_desktop_shortcut(title: str) -> None:
    """便携包运行时自动创建或修正桌面快捷方式，不走安装程序。"""
    if os.name != "nt" or not getattr(sys, "frozen", False):
        return
    root = portable_root_dir()
    if not (root / "source").exists():
        return
    desktop = Path(os.path.join(os.environ.get("USERPROFILE", str(Path.home())), "Desktop"))
    shortcut_path = desktop / f"{title}.lnk"
    exe_path = str(Path(sys.executable).resolve())
    icon_name = "app_icon_v85.ico"
    icon_path = root / "source" / "assets" / icon_name
    icon_location = f"{icon_path.resolve()},0" if icon_path.exists() else f"{exe_path},0"
    if title == "多云管理":
        stale_names = ("华为云管理.lnk", "天翼云管理.lnk", "火山引擎管理.lnk")
        stale_list = ", ".join("'" + name.replace("'", "''") + "'" for name in stale_names)
        cleanup_script = f"""
$Shell = New-Object -ComObject WScript.Shell
$CurrentTarget = '{exe_path.replace("'", "''")}'
$CurrentWorkDir = '{str(root).replace("'", "''")}'
foreach ($Name in @({stale_list})) {{
    $Path = Join-Path '{str(desktop).replace("'", "''")}' $Name
    if (Test-Path -LiteralPath $Path) {{
        try {{
            $Shortcut = $Shell.CreateShortcut($Path)
            if ([string]::Equals($Shortcut.TargetPath, $CurrentTarget, [System.StringComparison]::OrdinalIgnoreCase) -and [string]::Equals($Shortcut.WorkingDirectory, $CurrentWorkDir, [System.StringComparison]::OrdinalIgnoreCase)) {{
                Remove-Item -LiteralPath $Path -Force
            }}
        }} catch {{}}
    }}
}}
"""
        try:
            subprocess.run(
                ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", cleanup_script],
                check=False,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
            )
        except Exception:
            pass
    script = f"""
$Shell = New-Object -ComObject WScript.Shell
$Shortcut = $Shell.CreateShortcut('{str(shortcut_path).replace("'", "''")}')
$Shortcut.TargetPath = '{exe_path.replace("'", "''")}'
$Shortcut.WorkingDirectory = '{str(root).replace("'", "''")}'
$Shortcut.IconLocation = '{icon_location.replace("'", "''")}'
$Shortcut.Description = '{title.replace("'", "''")}'
$Shortcut.Save()
"""
    try:
        subprocess.run(
            ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
            check=False,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            creationflags=subprocess.CREATE_NO_WINDOW if hasattr(subprocess, "CREATE_NO_WINDOW") else 0,
        )
    except Exception:
        return
