#!/usr/bin/env python3
"""Setup script for AITop."""

from pathlib import Path
from typing import List, Optional, Set

from setuptools import find_packages, setup


def _read_version() -> str:
    """Load package version from aitop/version.py without importing package."""
    version_ns = {}
    version_file = Path(__file__).parent / "aitop" / "version.py"
    exec(version_file.read_text(encoding="utf-8"), version_ns)
    return str(version_ns["__version__"])


def _read_requirements(filename: str, seen: Optional[Set[str]] = None) -> List[str]:
    """Read requirements file with support for nested -r includes."""
    if seen is None:
        seen = set()

    if filename in seen:
        return []
    seen.add(filename)

    project_dir = Path(__file__).parent
    requirements_path = project_dir / filename
    requirements: List[str] = []

    for raw_line in requirements_path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue

        if line.startswith("-r "):
            nested_file = line[3:].strip()
            requirements.extend(_read_requirements(nested_file, seen))
            continue

        if line.startswith("--requirement "):
            nested_file = line[len("--requirement ") :].strip()
            requirements.extend(_read_requirements(nested_file, seen))
            continue

        # Support inline comments while preserving valid requirement specifiers.
        requirement = line.split(" #", 1)[0].strip()
        if requirement:
            requirements.append(requirement)

    deduped_requirements: List[str] = []
    dedupe_seen: Set[str] = set()
    for requirement in requirements:
        if requirement not in dedupe_seen:
            dedupe_seen.add(requirement)
            deduped_requirements.append(requirement)

    return deduped_requirements


# Read README.md for long description
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text(encoding="utf-8")
install_requires = _read_requirements("requirements.txt")
dev_requires = _read_requirements("requirements-dev.txt")
docs_requires = _read_requirements("requirements-docs.txt")

setup(
    name="aitop",
    version=_read_version(),
    description=(
        "AI/ML system monitor with mixed-vendor GPU/NPU telemetry, "
        "AI-process intelligence, and Linux + experimental macOS support"
    ),
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="Alexander Warth",
    author_email="alexander.warth@mailbox.org",
    license="MIT",
    url="https://gitlab.com/CochainComplex/aitop",
    project_urls={
        "Homepage": "https://gitlab.com/CochainComplex/aitop",
        "Source": "https://gitlab.com/CochainComplex/aitop",
        "Bug Tracker": "https://gitlab.com/CochainComplex/aitop/-/issues",
        "Author Website": "https://warth.ai",
    },
    packages=find_packages(),
    include_package_data=True,
    install_requires=install_requires,
    extras_require={
        "dev": dev_requires,
        "docs": docs_requires,
    },
    entry_points={
        "console_scripts": [
            "aitop=aitop.__main__:main",
        ],
    },
    package_data={
        "aitop": ["config/*.json"],
    },
    python_requires=">=3.9",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console :: Curses",
        "Intended Audience :: Developers",
        "Intended Audience :: System Administrators",
        "Operating System :: POSIX :: Linux",
        "Operating System :: MacOS :: MacOS X",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: 3.12",
        "Topic :: System :: Monitoring",
    ],
)
