#!/usr/bin/env python3
"""Workweaver portable ww launcher — never shebang a Homebrew python@ keg."""
from __future__ import annotations

import os
import sys
from pathlib import Path


def _here() -> Path:
    return Path(__file__).resolve()


def _is_keg(path: Path) -> bool:
    return "python@" in path.name


def _formula_venv_python(here: Path) -> Path | None:
    candidates = (
        here.parent / "python3",
        here.parent / "python",
        here.parent.parent / "libexec" / "bin" / "python3",
    )
    for candidate in candidates:
        if _is_keg(candidate):
            continue
        if candidate.is_file() and os.access(candidate, os.X_OK):
            return candidate
    return None


def _maybe_reexec(here: Path) -> None:
    override = str(os.environ.get("WW_PYTHON") or "").strip()
    target: Path | None = None
    if override and not _is_keg(Path(override)):
        candidate = Path(override)
        if candidate.is_file() and os.access(candidate, os.X_OK):
            target = candidate
    if target is None:
        target = _formula_venv_python(here)
    if target is None:
        return
    try:
        if target.resolve() == Path(sys.executable).resolve():
            return
    except OSError:
        return
    os.execv(str(target), [str(target), str(here), *sys.argv[1:]])


def _add_path(entries: list[str], seen: set[str], path: Path) -> None:
    try:
        resolved = str(path)
    except OSError:
        return
    if resolved in seen or not path.exists():
        return
    seen.add(resolved)
    entries.append(resolved)


def _prefix_entries(here: Path) -> list[str]:
    entries: list[str] = []
    seen: set[str] = set()
    env_prefix = str(os.environ.get("WW_PREFIX") or "").strip()
    if env_prefix:
        _add_path(entries, seen, Path(env_prefix))
    prefix = here.parent.parent
    _add_path(entries, seen, prefix)
    lib = prefix / "lib"
    if lib.is_dir():
        for site in sorted(lib.glob("python*/site-packages")):
            _add_path(entries, seen, site)
    libexec = prefix / "libexec"
    if libexec.is_dir():
        for site in sorted(
            libexec.glob("lib/python*/site-packages"),
            key=str,
        ):
            _add_path(entries, seen, site)
        for site in sorted(libexec.glob("**/site-packages"), key=str):
            _add_path(entries, seen, site)
    for ancestor in here.parents:
        if (ancestor / "apps" / "cli" / "ww").is_dir():
            _add_path(entries, seen, ancestor)
            break
    return entries


def _inject_prefix(here: Path) -> None:
    for entry in reversed(_prefix_entries(here)):
        while entry in sys.path:
            sys.path.remove(entry)
        sys.path.insert(0, entry)


def main() -> None:
    here = _here()
    _maybe_reexec(here)
    _inject_prefix(here)
    try:
        from workweaver.__main__ import main as _cli_main
    except ImportError:
        from apps.cli.ww.__main__ import main as _cli_main
    raise SystemExit(_cli_main())


if __name__ == "__main__":
    main()
