from __future__ import annotations

import os
import json
import subprocess
import sys
from pathlib import Path

from . import __version__


ENV_RUNTIME_BINARY = "OMNIDRAW_BIN"


def _packaged_binary_path() -> Path:
    binary_name = "omnidraw.exe" if os.name == "nt" else "omnidraw"
    return Path(__file__).resolve().parent / "bin" / binary_name


def resolve_binary() -> Path:
    override = os.environ.get(ENV_RUNTIME_BINARY)
    candidates = [Path(override)] if override else []
    candidates.append(_packaged_binary_path())
    for candidate in candidates:
        if candidate.exists() and candidate.is_file():
            return candidate
    checked = "\n".join(f"- {path}" for path in candidates)
    raise SystemExit(
        "OmniDraw binary not found.\n"
        f"Set {ENV_RUNTIME_BINARY} to a valid omnidraw binary, or reinstall the package.\n"
        f"Checked:\n{checked}"
    )


def _diagnostics() -> dict[str, object]:
    override = os.environ.get(ENV_RUNTIME_BINARY)
    binary = resolve_binary()
    return {
        "launcher_version": __version__,
        "binary_path": str(binary),
        "binary_exists": binary.exists(),
        "runtime_override": override,
        "platform": sys.platform,
    }


def main() -> int:
    if len(sys.argv) >= 2 and sys.argv[1] == "--print-binary-path":
        print(resolve_binary())
        return 0

    if len(sys.argv) >= 2 and sys.argv[1] == "--launcher-diagnostics":
        print(json.dumps(_diagnostics(), indent=2))
        return 0

    binary = resolve_binary()
    completed = subprocess.run([str(binary), *sys.argv[1:]], check=False)
    return int(completed.returncode)


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