import re
import subprocess
from setuptools import setup

COMPONENT_NAME = "internal"


def version_scheme(version):
    """Custom version scheme for internal/monorepo builds.

    Parses the git tag message to find component-specific version.
    Tag message format: "Release v2026.02.04-dev2 packages: internal: 0.3.2.dev2 ..."
    """
    tag = str(version.tag)
    distance = version.distance or 0

    try:
        # Get the actual git tag name (not the normalized version from packaging.version)
        raw_tag = subprocess.check_output(
            ["git", "describe", "--tags", "--abbrev=0"],
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()

        # Get the tag message using the raw tag name
        tag_message = subprocess.check_output(
            ["git", "tag", "-l", "--format=%(contents:subject)", raw_tag],
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()

        # Parse component version from tag message
        pattern = rf'{COMPONENT_NAME}:\s*(\d+\.\d+\.\d+)(?:\.dev(\d+))?'
        match = re.search(pattern, tag_message)

        if match:
            base_version = match.group(1)
            tag_dev = int(match.group(2)) if match.group(2) else 0
            dev_num = tag_dev + distance

            if dev_num == 0:
                return base_version
            return f"{base_version}.dev{dev_num}"

    except subprocess.CalledProcessError:
        pass

    # Fallback: use tag as version (for external repos or missing component)
    tag_match = re.match(r'^v?(\d+\.\d+\.\d+)(?:\.dev(\d+))?$', tag)
    if tag_match:
        base_version = tag_match.group(1)
        tag_dev = int(tag_match.group(2)) if tag_match.group(2) else 0
        dev_num = tag_dev + distance

        if dev_num == 0:
            return base_version
        return f"{base_version}.dev{dev_num}"

    return "0.0.0.dev0"


setup(
    use_scm_version={
        "root": "..",
        "version_scheme": version_scheme,
        "local_scheme": "no-local-version",
    }
)
