"""Automatic Python version detection for Bazel build.

This repository rule detects the system Python version and provides
generates version information for wheel building.
"""

def _python_detect_impl(repository_ctx):
    # Check if PYTHON_VERSION is explicitly set in environment
    env_python_version = repository_ctx.os.environ.get("PYTHON_VERSION")

    detected_major = "3"
    detected_minor = "11"  # Default to 3.11

    if env_python_version:
        # Use explicitly specified PYTHON_VERSION
        parts = env_python_version.split(".")
        if len(parts) >= 2:
            detected_major = parts[0]
            detected_minor = parts[1]
            print("Using PYTHON_VERSION from environment: {}.{}".format(detected_major, detected_minor))
    else:
        # Auto-detect from system python3
        result = repository_ctx.execute(["python3", "--version"])
        if result.return_code != 0:
            # Fallback to python
            result = repository_ctx.execute(["python", "--version"])

        if result.return_code == 0:
            # python --version output can be on stdout or stderr depending on Python version
            output = result.stdout.strip()
            if not output:
                output = result.stderr.strip()

            # Parse output like "Python 3.11.4" → extract "3.11"
            first_line = output.splitlines()[0]
            version_str = first_line.replace("Python", "").replace("python", "").strip()
            parts = version_str.split(".")
            if len(parts) >= 2:
                detected_major = parts[0]
                detected_minor = parts[1]

    python_version = "{detected_major}.{detected_minor}".format(
        detected_major = detected_major,
        detected_minor = detected_minor,
    )

    # Generate the version file
    repository_ctx.file("version.bzl", content = '''# Auto-generated by python version detection
# DO NOT EDIT - changes will be overwritten on next bazel build
#
# Detected Python version: {detected_major}.{detected_minor}

PYTHON_MAJOR = "{detected_major}"
PYTHON_MINOR = "{detected_minor}"
PYTHON_VERSION = "{detected_major}.{detected_minor}"
'''.format(
        detected_major = detected_major,
        detected_minor = detected_minor,
    ))

    repository_ctx.file("BUILD.bazel", "")

python_detect = repository_rule(
    implementation = _python_detect_impl,
    local = True,
    environ = ["PATH", "PYTHON_VERSION"],
)