"""Detect how the application was installed.

The install type determines which update strategy is available:
- installer: NSIS `.exe` installed to AppData — can run new installer silently
- portable:  Extracted ZIP with embedded Python — can replace app/ + python/ dirs
- docker:    Running inside a Docker container — no auto-update, show instructions
- dev:       Running from source (pip install -e) — no auto-update, link to releases
"""

import sys
from enum import Enum
from pathlib import Path

from wled_controller.utils import get_logger

logger = get_logger(__name__)


class InstallType(str, Enum):
    INSTALLER = "installer"
    PORTABLE = "portable"
    DOCKER = "docker"
    DEV = "dev"


def detect_install_type() -> InstallType:
    """Detect the current install type once at startup."""
    # Docker: /.dockerenv file or cgroup hints
    if Path("/.dockerenv").exists():
        logger.info("Install type: docker")
        return InstallType.DOCKER

    # Windows installed/portable: look for embedded Python dir
    app_root = Path.cwd()
    has_uninstaller = (app_root / "uninstall.exe").exists()
    has_embedded_python = (app_root / "python" / "python.exe").exists()

    if has_uninstaller:
        logger.info("Install type: installer (uninstall.exe found at %s)", app_root)
        return InstallType.INSTALLER

    if has_embedded_python:
        logger.info("Install type: portable (embedded python/ found at %s)", app_root)
        return InstallType.PORTABLE

    # Linux portable: look for venv/ + run.sh
    if (app_root / "venv").is_dir() and (app_root / "run.sh").exists():
        logger.info("Install type: portable (Linux venv layout at %s)", app_root)
        return InstallType.PORTABLE

    logger.info("Install type: dev (no distribution markers found)")
    return InstallType.DEV


def get_platform_asset_pattern(install_type: InstallType) -> str | None:
    """Return a substring that the matching release asset name must contain.

    Returns None if auto-update is not supported for this install type.
    """
    if install_type == InstallType.DOCKER:
        return None
    if install_type == InstallType.DEV:
        return None

    if sys.platform == "win32":
        if install_type == InstallType.INSTALLER:
            return "-setup.exe"
        return "-win-x64.zip"

    if sys.platform == "linux":
        return "-linux-x64.tar.gz"

    return None
