#!/usr/bin/env python3
"""Launch pinghue with a resilient import path bootstrap.

This launcher avoids hard dependency on editable .pth processing by falling back
to the editable source root path captured in `direct_url.json` when available.
"""

from __future__ import annotations

import json
import sys
from collections.abc import Callable
from importlib import metadata
from pathlib import Path
from urllib.parse import unquote, urlparse

ImportProbeMain = Callable[[], Callable[[], int]]


def _direct_import_main() -> Callable[[], int]:
    """Return the installed entrypoint if the normal import path is healthy."""
    from pinghue.cli import main

    return main


def _load_main_entrypoint(
    *, importer: ImportProbeMain | None = None
) -> Callable[[], int]:
    """Return the package entrypoint without requiring import side-effects."""
    import_main = importer or _direct_import_main
    try:
        return import_main()
    except ModuleNotFoundError as exc:
        if exc.name != "pinghue":
            raise

    try:
        dist = metadata.distribution("pinghue")
        direct_url = dist.read_text("direct_url.json")
        if direct_url is None:
            raise FileNotFoundError
        payload = json.loads(direct_url)
    except (
        OSError,
        UnicodeError,
        json.JSONDecodeError,
        metadata.PackageNotFoundError,
    ):
        raise RuntimeError("pinghue package metadata is not available") from None

    if not isinstance(payload, dict):
        raise RuntimeError("unexpected pinghue package metadata")

    dir_info = payload.get("dir_info")
    if not isinstance(dir_info, dict):
        raise RuntimeError("unexpected pinghue package metadata")

    if dir_info.get("editable") is not True:
        raise RuntimeError("pinghue was not installed as editable")

    raw_url = payload.get("url")
    if not isinstance(raw_url, str):
        raise RuntimeError("unexpected editable source URL in pinghue metadata")

    parsed_url = urlparse(raw_url)
    source_path = unquote(parsed_url.path)
    if (
        parsed_url.scheme != "file"
        or parsed_url.netloc not in {"", "localhost"}
        or not source_path.startswith("/")
        or "\x00" in source_path
    ):
        raise RuntimeError("unexpected editable source URL in pinghue metadata")

    source_root = Path(source_path)
    candidate_paths = [source_root / "src", source_root]
    for candidate in candidate_paths:
        candidate_text = str(candidate)
        sys.path.insert(0, candidate_text)
        try:
            from pinghue.cli import main
        except ModuleNotFoundError as exc:
            sys.path.remove(candidate_text)
            if exc.name not in {"pinghue", "pinghue.cli"}:
                raise
            continue
        except BaseException:
            sys.path.remove(candidate_text)
            raise
        else:
            return main

    raise RuntimeError("could not resolve pinghue source path for editable install")


def main() -> int:
    try:
        entrypoint = _load_main_entrypoint()
    except RuntimeError as exc:
        print(f"pinghue: unable to start: {exc}", file=sys.stderr)
        return 1
    return entrypoint()


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