"""Console entrypoints for Hikaflow CLI.

This wrapper keeps startup errors user-friendly when a command is executed
from the wrong Python environment.
"""

from __future__ import annotations

import os
import sys


def _print_env_mismatch_help() -> None:
    current_python = sys.executable
    cwd = os.getcwd()
    lines = [
        "Hikaflow CLI failed to start because required Python modules were not found.",
        f"Interpreter: {current_python}",
        f"Working directory: {cwd}",
        "",
        "This usually means `hikaflow` is being run from a different environment",
        "than the one where Hikaflow is installed.",
        "",
        "Fix:",
        "1) Activate your intended environment.",
        "2) Install Hikaflow into that environment:",
        "   python -m pip install -e .",
        "3) Run with the same interpreter:",
        "   python -m autodebug.cli_v2",
    ]
    print("\n".join(lines), file=sys.stderr)


def _fix_macos_hidden_flags() -> None:
    """Remove macOS UF_HIDDEN flags from site-packages .pth files.

    macOS sometimes sets these flags, causing Python to skip .pth files
    with "Skipping hidden .pth file" — which breaks editable installs.
    """
    if sys.platform != "darwin":
        return
    try:
        import site
        import subprocess
        for sp in site.getsitepackages():
            if os.path.isdir(sp):
                subprocess.run(
                    ["chflags", "-R", "nohidden", sp],
                    capture_output=True, timeout=5,
                )
    except Exception:
        pass


def main() -> int:
    # Fix macOS hidden flags that break .pth processing
    _fix_macos_hidden_flags()

    # Load .env from project root so ANTHROPIC_API_KEY etc. are available
    try:
        from dotenv import load_dotenv
        load_dotenv()
    except ImportError:
        pass

    try:
        from autodebug.cli_v2 import app
    except ModuleNotFoundError:
        _print_env_mismatch_help()
        return 1
    app()
    return 0


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