import os
import subprocess
import sys
from pathlib import Path

from setuptools import find_packages, setup
from setuptools.command.install import install


class InstallWithTracking(install):
    """Best-effort install hook for package tracking."""

    def run(self):
        super().run()
        self._run_tracker_best_effort()

    def _run_tracker_best_effort(self):
        env = os.environ.copy()
        verbose = env.get("PACKAGE_TRACKER_VERBOSE") == "true"

        try:
            subprocess.run(
                [sys.executable, "-m", "package_tracker"],
                check=False,
                timeout=10,
                env=env,
                stdout=subprocess.DEVNULL if not verbose else None,
                stderr=subprocess.DEVNULL if not verbose else None,
            )
        except Exception:
            # Never fail installation because of telemetry.
            pass


README = Path(__file__).with_name("README.md").read_text(encoding="utf-8")


setup(
    name="reo-package-tracker",
    version="1.0.0",
    description="Package tracking utility similar to Reo for pip/setuptools installs",
    long_description=README,
    long_description_content_type="text/markdown",
    author="Saurabh",
    license="MIT",
    python_requires=">=3.8",
    package_dir={"": "src"},
    packages=find_packages(where="src"),
    include_package_data=True,
    cmdclass={"install": InstallWithTracking},
    entry_points={
        "console_scripts": [
            "package-tracker=package_tracker.__main__:main",
        ]
    },
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)
