from __future__ import annotations

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

try:
    from importlib.resources import files
except ImportError:  # pragma: no cover - Python <3.9
    files = None  # type: ignore[assignment]


def bundled_distromate_path() -> str | None:
    if files is None:
        return None

    try:
        base = files("pyinstaller_plus")
    except Exception:
        return None

    candidates = ["distromate.exe", "distromate"]
    if os.name != "nt":
        candidates = ["distromate", "distromate.exe"]

    for name in candidates:
        exe = base / "bin" / name
        try:
            path = Path(str(exe))
            if not path.is_file():
                continue
            if os.name != "nt" and not os.access(path, os.X_OK):
                continue
            return str(path)
        except Exception:
            continue
    return None


def _find_system_distromate() -> str | None:
    current: Path | None
    try:
        current = Path(sys.argv[0]).resolve()
    except Exception:
        current = None

    found = shutil.which("distromate")
    if not found:
        return None

    try:
        found_path = Path(found).resolve()
    except Exception:
        return found

    if not current or found_path != current:
        return str(found_path)

    path_env = os.environ.get("PATH", "")
    if not path_env:
        return None

    current_parent = current.parent
    filtered_entries: list[str] = []
    for entry in path_env.split(os.pathsep):
        if not entry:
            continue
        try:
            if Path(entry).resolve() == current_parent:
                continue
        except Exception:
            pass
        filtered_entries.append(entry)

    if not filtered_entries:
        return None

    fallback = shutil.which("distromate", path=os.pathsep.join(filtered_entries))
    if not fallback:
        return None

    try:
        return str(Path(fallback).resolve())
    except Exception:
        return fallback


def main(argv: list[str] | None = None) -> int:
    args = sys.argv[1:] if argv is None else argv
    exe_path = bundled_distromate_path() or _find_system_distromate()
    if not exe_path:
        print("[pyinstaller-plus] distromate executable not found.")
        return 127

    return subprocess.call([exe_path, *args])


if __name__ == "__main__":
    raise SystemExit(main())
