#!/usr/bin/env python3
"""gtheme launcher — runs from a source checkout without installation.

Adds the repo's ``src`` to sys.path so ``gtheme`` works the moment the repo is
cloned, as long as Python can import jinja2 and pydantic.
"""
import sys
from pathlib import Path

# Python version gate first: gtheme needs 3.11+ for tomllib. Without this, an
# old interpreter fails importing tomllib and gets misreported as a jinja2/
# pydantic problem below.
_PY_311_FIX = (
    "(Ubuntu 22.04 ships 3.10 — upgrade to 24.04+, or install gtheme with a "
    "newer Python, e.g.: uv tool install --python 3.12 .)\n"
)
if sys.version_info < (3, 11):
    sys.stderr.write(
        "gtheme needs Python 3.11+ (for the stdlib 'tomllib'); "
        f"found {sys.version_info.major}.{sys.version_info.minor}\n" + _PY_311_FIX
    )
    raise SystemExit(1)

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

# Mirrors install.sh's guidance() — a bare `pip install` is rejected by PEP 668
# on every modern distro, so never suggest it.
_DEP_FIX = (
    "fix (pick one):\n"
    "    ./install.sh --pip   (run from the gtheme folder — private venv, any distro)\n"
    "    Debian/Ubuntu:  sudo apt install python3-jinja2 python3-pydantic\n"
    "                    (Debian 12 / Ubuntu 24.04 apt ships pydantic 1.x — prefer --pip there)\n"
    "    Fedora:         sudo dnf install python3-jinja2 python3-pydantic\n"
    "    Arch:           sudo pacman -S python-jinja2 python-pydantic\n"
)


def _dep_diagnosis() -> str:
    """One human line for the common dependency failures, or '' if unknown."""
    try:
        import pydantic
    except ImportError:
        return "the 'pydantic' module is not installed"
    # pydantic 1.x (Debian 12 / Ubuntu 24.04 apt) imports fine but lacks the
    # v2-only names gtheme uses; VERSION exists on both major versions.
    ver = str(getattr(pydantic, "VERSION", "") or getattr(pydantic, "__version__", ""))
    major = ver.split(".")[0]
    if major.isdigit() and int(major) < 2:
        return f"your distro ships pydantic {ver}; gtheme needs 2.x"
    try:
        import jinja2
    except ImportError:
        return "the 'jinja2' module is not installed"
    jver = str(getattr(jinja2, "__version__", ""))
    jparts = jver.split(".")
    if len(jparts) >= 2 and jparts[0].isdigit() and jparts[1].isdigit():
        if (int(jparts[0]), int(jparts[1])) < (3, 1):
            return f"jinja2 {jver} is too old; gtheme needs 3.1+"
    return ""


try:
    from gtheme.cli import main  # noqa: E402
except ImportError as exc:
    # Catch ImportError, not just ModuleNotFoundError: pydantic 1.x imports
    # fine and then raises a *plain* ImportError on the v2-only names.
    missing = getattr(exc, "name", "") or str(exc)
    if missing == "tomllib":
        sys.stderr.write(
            "gtheme needs Python 3.11+ (for the stdlib 'tomllib')\n" + _PY_311_FIX
        )
    else:
        reason = _dep_diagnosis() or str(exc)
        sys.stderr.write(f"gtheme could not start: {reason}\n" + _DEP_FIX)
    raise SystemExit(1)

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