"""mithril CLI entrypoint: call into Rust pyo3 module or delegate to Python CLI."""

from __future__ import annotations

import platform
import sys


def main() -> int:
    """Entrypoint for mithril command."""
    # Delegate top-level help to Python for unified help output
    # Top-level means: "ml -h", "ml --help", or "ml help" (with no subcommand after)
    # PLR2004: 2 = program name + help flag, i.e. exactly one argument provided
    if len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help", "help"):  # noqa: PLR2004
        from mithril.cli.main import cli  # noqa: PLC0415

        return cli()

    try:
        # Deferred import: Rust extension may not be available on all platforms
        from mithril._mcli import run  # noqa: PLC0415
    except ImportError:
        return _handle_missing_extension()

    result = run(sys.argv)

    # Return code -1 means delegate to Python CLI
    if result == -1:
        # Deferred import: only load Python CLI when Rust CLI delegates to it
        from mithril.cli.main import cli  # noqa: PLC0415

        return cli()

    return result


def _handle_missing_extension() -> int:
    os_name = platform.system()
    arch = platform.machine()

    supported = [
        ("Linux", "x86_64"),
        ("Linux", "aarch64"),
        ("Darwin", "x86_64"),
        ("Darwin", "arm64"),
    ]

    is_supported = (os_name, arch) in supported

    print("mithril: Native extension not available", file=sys.stderr)
    print(file=sys.stderr)

    if not is_supported:
        print(
            f"Your platform ({os_name} {arch}) is not yet supported.", file=sys.stderr
        )
        print(
            "Supported platforms: macOS (x86_64, arm64), Linux (x86_64, arm64)",
            file=sys.stderr,
        )
    else:
        print("This may happen if:", file=sys.stderr)
        print("  - You installed from source without Rust toolchain", file=sys.stderr)
        print("  - The wheel was built for a different Python version", file=sys.stderr)
        print(file=sys.stderr)
        print(
            "Try reinstalling: pip install --force-reinstall mithril-client",
            file=sys.stderr,
        )

    return 1


if __name__ == "__main__":
    sys.exit(main())
