import os
import sys
import subprocess
from setuptools import setup, Extension

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.abspath(os.path.join(HERE, "..", ".."))

library_dirs = []
include_dirs = [os.environ.get("FASTQ_INCLUDE_DIR", os.path.join(ROOT, "include"))]

if sys.platform == "darwin":
    for pkg in ["openssl", "hiredis", "json-c"]:
        try:
            prefix = subprocess.check_output(
                ["brew", "--prefix", pkg], stderr=subprocess.DEVNULL
            ).decode().strip()
            library_dirs.append(os.path.join(prefix, "lib"))
            include_dirs.append(os.path.join(prefix, "include"))
        except Exception:
            pass
elif sys.platform.startswith("linux"):
    library_dirs += ["/usr/lib64", "/usr/lib"]

fastq_pic = os.environ.get(
    "FASTQ_LIB_DIR", os.path.join(ROOT, "build", "libfastq_pic.a")
)

fastq_ext = Extension(
    "fastq",
    sources=["fastq_module.c"],
    include_dirs=include_dirs,
    library_dirs=library_dirs,
    extra_objects=[fastq_pic],
    libraries=["hiredis", "json-c", "pthread", "ssl", "crypto"],
)

try:
    long_description = open(os.path.join(ROOT, "README.md")).read()
except FileNotFoundError:
    long_description = ""

setup(
    name="fastq-redis",
    version=os.environ.get("FASTQ_VERSION", "1.0.0").lstrip("v"),
    description="Python bindings for FastQ — high-performance Redis job queue written in C",
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="Arlen Ghost",
    author_email="support@fastq.oxoghost.dev",
    url="https://github.com/OxoGhost01/FastQ",
    license="PolyForm Noncommercial 1.0.0",
    python_requires=">=3.8",
    classifiers=[
        "Programming Language :: Python :: 3",
        "Programming Language :: C",
        "Operating System :: POSIX :: Linux",
        "Topic :: System :: Distributed Computing",
    ],
    ext_modules=[fastq_ext],
)
