#!/usr/bin/env python3
"""
Setup script for GPATHEX

Genbinesia Pathway Extractor
"""
import os
import sys
from setuptools import setup, find_packages
from pathlib import Path

# Check Python version
if sys.version_info < (3, 11):
    sys.exit("gpathex requires Python 3.11 or higher!")

# Read version from package
def get_version():
    """Read version from __init__.py."""
    version_file = Path(__file__).parent / "gpathex" / "__init__.py"
    with open(version_file, "r", encoding="utf-8") as f:
        for line in f:
            if line.startswith("__version__"):
                return line.split("=")[1].strip().strip('"\'')
    return "1.0.0"

# Read long description from README
def get_long_description():
    """Read long description from README.md."""
    readme_path = Path(__file__).parent / "README.md"
    if readme_path.exists():
        try:
            return readme_path.read_text(encoding="utf-8")
        except Exception as e:
            print(f"Warning: Could not read README.md: {e}")
    return "Genbinesia Pathway Extractor"

# Get requirements from requirements.txt
def get_requirements():
    """Read requirements from requirements.txt."""
    req_path = Path(__file__).parent / "requirements.txt"
    if req_path.exists():
        with open(req_path, "r", encoding="utf-8") as f:
            return [
                line.strip()
                for line in f
                if line.strip() and not line.startswith("#")
            ]
    return []

# Get development requirements
def get_dev_requirements():
    """Get development dependencies."""
    return [
        "pytest>=9.0.2",
        "pytest-cov>=7.0.0",
        "pytest-mock>=3.15.1",
        "pytest-xdist>=3.8.0",
        "black>=26.1.0",
        "mypy>=1.19.1",
        "ruff>=0.14.14",
        "pre-commit>=4.5.1",
        "twine>=6.2.0",
        "build>=1.4.0",
        "sphinx>=7.0.0",
        "sphinx-rtd-theme>=3.1.0",
        "sphinx-autodoc-typehints>=3.6.2",
    ]

# Package metadata
NAME = "gpathex"
VERSION = get_version()
DESCRIPTION = "Genbinesia Pathway Extractor"
LONG_DESCRIPTION = get_long_description()
LONG_DESCRIPTION_CONTENT_TYPE = "text/markdown"
AUTHOR = "Maulana Malik Nashrulloh"
AUTHOR_EMAIL = "maulana@genbinesia.or.id"
URL = "https://gitlab.com/biomikalab/gpathex "
LICENSE = "GPLv3"
PYTHON_REQUIRES = ">=3.11"
CLASSIFIERS = [
    # Development Status
    "Development Status :: 4 - Beta",
    "Intended Audience :: Science/Research",
    "Topic :: Scientific/Engineering :: Bio-Informatics",
        
    # License
    "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
    
    # Python versions
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
    "Programming Language :: Python :: 3.13",
    "Programming Language :: Python :: 3.14",
    
    # Operating Systems
    "Operating System :: POSIX :: Linux",
    
    # Additional metadata
    "Natural Language :: English",
]

# Core dependencies
INSTALL_REQUIRES = [
    "polars>=1.37.1",      # Fast DataFrame operations
    "biopython>=1.86",     # Biological computation and KEGG API
]

# Optional dependencies
EXTRAS_REQUIRE = {
    # Fast FASTA parsing (optional but recommended)
    "fast": [
        "polars-bio>=0.19.0",
    ],
    
    # Visualization (for plot-keg command)
    "viz": [
        "matplotlib>=3.10.8",
        "seaborn>=0.13.2",  # Better visualizations
    ],
    
    # Enhanced CLI experience
    "cli": [
        "rich>=14.2.0",        # Beautiful terminal output
        "tqdm>=4.67.1",         # Progress bars
        "colorama>=0.4.6",      # Cross-platform colored output
        "click>=8.3.1",         # Better CLI framework (optional)
    ],
    
    # Additional file format support
    "formats": [
        "pyarrow>=21.0.0",     # Better Parquet support
        "openpyxl>=3.1.5",      # Excel support
        "orjson>=3.11.5",       # Fast JSON
    ],
    
    # Network and API enhancements
    "network": [
        "aiohttp>=3.13.3",       # Async HTTP
        "httpx>=0.28.1",        # Modern HTTP client
        "backoff>=2.2.1",       # Exponential backoff
    ],
    
    # Development and testing
    "dev": get_dev_requirements(),
    
    # Testing (subset of dev)
    "test": [
        "pytest>=9.0.2",
        "pytest-cov>=7.0.0",
        "pytest-mock>=3.15.1",
        "pytest-xdist>=3.8.0",
    ],
    
    # Documentation
    "docs": [
        "sphinx>=9.1.0",
        "sphinx-rtd-theme>=3.1.0",
        "sphinx-autodoc-typehints>=3.6.2",
        "sphinx-copybutton>=0.5.2",
        "myst-parser>=5.0.0",
    ],
    
    # Complete package with all optional features
    "all": [
        "polars-bio>=0.19.0",
        "matplotlib>=3.10.8",
        "seaborn>=0.13.2",
        "rich>=14.2.0",
        "tqdm>=4.67.1",
        "colorama>=0.4.6",
        "pyarrow>=21.0.0",
        "openpyxl>=3.1.5",
        "orjson>=3.11.5",
        "aiohttp>=3.13.3",
        "httpx>=0.28.1",
        "backoff>=2.2.1",
    ],
    
    # Production deployment
    "production": [
        "polars-bio>=0.19.0",   # Fast FASTA parsing
        "rich>=14.2.0",         # Good logging
        "pyarrow>=21.0.0",      # Parquet support
        "backoff>=2.2.1",       # Retry logic
    ],
}

# Entry points
ENTRY_POINTS = {
    "console_scripts": [
        # Main command: gpathex (short & sweet)
        "gpathex=gpathex.cli:main",
        
        # Alias: gp  (for clarity in scripts)
        "gpe =gpathex.cli:main",
        
        # Individual command shortcuts (optional)
        "gpathex-download-org=gpathex.commands.download_org:main",
        "gpathex-download-ko=gpathex.commands.download_ko:main",
        "gpathex-download-proteins=gpathex.commands.download_proteins:main",
        "gpathex-make-db=gpathex.commands.makedb:main",
    ],
}

# Package discovery
PACKAGES = find_packages(
    where=".",
    include=["gpathex", "gpathex.*"],
    exclude=["tests", "tests.*", "docs", "docs.*", "examples", "examples.*"],
)

# Package data
PACKAGE_DATA = {
    "gpathex": [
        # Include any non-Python files in the package
        "py.typed",  # For type checking
    ],
}

# Data files (non-Python files)
# DATA_FILES = [
    # # Optional: include example data
    # ("share/gpathex/examples", [
        # "examples/basic_workflow.py",
        # "examples/custom_database.py",
    # ]),
# ]

# Setup configuration
setup(
    # Basic information
    name=NAME,
    version=VERSION,
    description=DESCRIPTION,
    long_description=LONG_DESCRIPTION,
    long_description_content_type=LONG_DESCRIPTION_CONTENT_TYPE,
    
    # Author information
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    maintainer=AUTHOR,
    maintainer_email=AUTHOR_EMAIL,
    
    # Project URLs
    url=URL,
    project_urls={
        "Homepage": URL,
        "Documentation": f"{URL}/blob/main/README.md",
        "Repository": URL,
        "Issues": f"{URL}/issues",
        "Changelog": f"{URL}/releases",
        "Download": f"https://pypi.org/project/{NAME}/",
    },
    
    # License
    license=LICENSE,
    license_files=["LICENSE"],
    
    # Classifiers
    classifiers=CLASSIFIERS,
    
    # Keywords
    keywords=[
        "bioinformatics",
        "kegg",
        "genomics",
        "proteomics",
        "metabolomics",
        "pathway",
        "orthology",
        "database",
        "cli",
        "polars",
        "biopython",
        "fasta",
        "annotation",
        "visualization",
    ],
    
    # Python requirements
    python_requires=PYTHON_REQUIRES,
    
    # Dependencies
    install_requires=INSTALL_REQUIRES,
    extras_require=EXTRAS_REQUIRE,
    
    # Packages
    packages=PACKAGES,
    package_dir={"": "."},
    include_package_data=True,
    package_data=PACKAGE_DATA,
    
    # Entry points
    entry_points=ENTRY_POINTS,
    
    # Data files
    # data_files=DATA_FILES,
    
    # Scripts (alternative to entry_points)
    scripts=[],
    
    # Additional options
    zip_safe=False,  # Not zip safe due to config files
    platforms=["any"],
    
    # Command line options for setuptools
    options={
        "bdist_wheel": {
            "universal": False,  # Pure Python but not version independent
        },
        "egg_info": {
            "tag_build": "",  # No build tag
            "tag_date": False,
        },
    },
    
    # Custom setup commands
    cmdclass={},
    
    # Test suite
    test_suite="tests",
    tests_require=EXTRAS_REQUIRE["test"],
    
    # For type checking
    typed="py.typed",
)

# Post-install message
def print_post_install_message():
    """Print helpful message after installation."""
    message = f"""
    
    Successfully installed {NAME} v{VERSION}!
    
    Get started with:
    
      gpathex info                    # Show system information
      gpathex --help                  # Show all commands
      gpathex download-org --help     # Get help for specific command
    
    Documentation: {URL}
    
    Pro tip: Install with all features:
      pip install '{NAME}[all]'
    
    Example workflow:
      1. gpathex download-org --out organisms.tsv
      2. gpathex download-ko --org organisms.tsv --out ko_files
      3. gpathex download-proteins --org organisms.tsv --out proteins
      4. gpathex make-db --org organisms.tsv --keg ko_files --pep proteins --out my_db
    
    Note: If something happened, use 'gpe' instead of 'gpathex'
    
    Happy using gpathex!
    """
    print(message)

# Run post-install message if this is an install
if len(sys.argv) > 1 and sys.argv[1] in ["install", "develop", "bdist_wheel", "bdist_egg"]:
    try:
        print_post_install_message()
    except:
        pass  # Silently fail if something goes wrong
        