"""Setup script with optional mypyc compilation."""
import os
import glob
from setuptools import setup, find_packages
from typing import List

# =============================================================================
# CONFIGURATION
# =============================================================================

# Environment variables control build behavior
ENABLE_MYPYC = os.environ.get("ENABLE_MYPYC", "").lower() in ("true", "1", "yes")

# Source directory
SRC_DIR = "src"
PACKAGE_NAME = "matrice_streaming"


def get_version() -> str:
    """Get version from environment or default."""
    return os.environ.get("PACKAGE_VERSION", "0.0.0.dev0")


def discover_modules() -> List[str]:
    """Discover all Python modules for mypyc compilation."""
    modules = []
    package_dir = os.path.join(SRC_DIR, PACKAGE_NAME)

    for py_file in glob.glob(f"{package_dir}/**/*.py", recursive=True):
        # Skip __init__.py, test files, and debug files
        basename = os.path.basename(py_file)
        if basename.startswith("_") or "test" in basename.lower():
            continue
        # Skip debug directory (not performance critical)
        if "debug" in py_file.replace("\\", "/"):
            continue
        modules.append(py_file)

    return modules


def get_ext_modules():
    """Get extension modules for mypyc compilation."""
    if not ENABLE_MYPYC:
        print("=" * 60)
        print("Building PURE PYTHON package (mypyc disabled)")
        print("=" * 60)
        return []

    try:
        from mypyc.build import mypycify
    except ImportError:
        print("WARNING: mypyc not available, building pure Python package")
        return []

    print("=" * 60)
    print("Building MYPYC COMPILED package")
    print("=" * 60)

    modules = discover_modules()
    print(f"Compiling {len(modules)} modules with mypyc")

    mypyc_options = [
        "--follow-imports=skip",
        "--ignore-missing-imports",
        "--disable-error-code=annotation-unchecked",
    ]

    return mypycify(mypyc_options + modules, opt_level="3")


# =============================================================================
# SETUP
# =============================================================================

setup(
    name=PACKAGE_NAME.replace("_", "-"),
    version=get_version(),
    packages=find_packages(where=SRC_DIR),
    package_dir={"": SRC_DIR},
    ext_modules=get_ext_modules(),
    python_requires=">=3.8",
    include_package_data=True,
    package_data={
        PACKAGE_NAME: ["py.typed", "**/*.pyi"],
    },
)
