# -*- coding: utf-8 -*-
"""Detect Claude Desktop install (product launches Store / desktop app)."""
from __future__ import annotations

import os
import subprocess
from pathlib import Path

CREATE_NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
PWSH = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
# Official Claude Desktop (Microsoft Store) AppUserModelID used by Start script
CLAUDE_AUMID = "Claude_pzs8sxrjxfjjc!Claude"


def claude_desktop_installed() -> tuple[bool, str]:
    """
    Return (installed, detail).
    Paths first (instant), then Store package — avoid slow AppsFolder COM scan.
    """
    home = Path(os.environ.get("USERPROFILE", ""))
    candidates = [
        home / "AppData" / "Local" / "Programs" / "claude" / "Claude.exe",
        home / "AppData" / "Local" / "AnthropicClaude" / "Claude.exe",
        Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Claude" / "Claude.exe",
    ]
    for c in candidates:
        if c.is_file():
            return True, str(c)

    try:
        p = subprocess.run(
            [
                str(PWSH),
                "-NoProfile",
                "-ExecutionPolicy",
                "Bypass",
                "-Command",
                "(Get-AppxPackage -Name 'Claude*' -ErrorAction SilentlyContinue | "
                "Select-Object -First 1 -ExpandProperty PackageFullName)",
            ],
            capture_output=True,
            text=True,
            timeout=8,
            creationflags=CREATE_NO_WINDOW,
        )
        pkg = (p.stdout or "").strip()
        if pkg:
            return True, f"Microsoft Store: {pkg}"
    except Exception:
        pass

    # Lightweight AUMID presence via Get-StartApps (faster than shell:AppsFolder enum)
    try:
        p = subprocess.run(
            [
                str(PWSH),
                "-NoProfile",
                "-ExecutionPolicy",
                "Bypass",
                "-Command",
                f"if (Get-StartApps -ErrorAction SilentlyContinue | "
                f"Where-Object {{ $_.AppID -eq '{CLAUDE_AUMID}' }} | Select-Object -First 1) "
                f"{{ 'yes' }} else {{ 'no' }}",
            ],
            capture_output=True,
            text=True,
            timeout=8,
            creationflags=CREATE_NO_WINDOW,
        )
        if "yes" in (p.stdout or "").lower():
            return True, f"StartApps: {CLAUDE_AUMID}"
    except Exception:
        pass

    return False, "Claude Desktop не найден (установите с claude.ai/download или Microsoft Store)"
