"""Installation file for the ansys-api-pyensight package"""

import os
import sys
from datetime import datetime

import setuptools
import setuptools.command.build_py
import setuptools.command.sdist

from ansys.tools.protoc_helper import CMDCLASS_OVERRIDE
import distutils.cmd
import distutils.log
import subprocess

# Get the long description from the README file
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md"), encoding="utf-8") as f:
    long_description = f.read()

product = "pyensight"
library = ""
package_info = ["ansys", "api", product, library, "v0"]
with open(os.path.join(HERE, "src", "ansys", "api", product, library, "VERSION"), encoding="utf-8") as f:
    version = f.read().strip()

package_name = "ansys-api-pyensight"
dot_package_name = '.'.join(filter(None, package_info))

description = f"Autogenerated python gRPC interface package for {package_name}, built on {datetime.now().strftime('%H:%M:%S on %d %B %Y')}"

class CodegenCommand(distutils.cmd.Command):
    """A custom command to run the generation of the Python stubs."""

    description = 'run generate.py'
    def initialize_options(self):
        pass
        
    def finalize_options(self):
        pass

    def run(self):
        """Run command."""
        path = os.path.join(os.path.dirname(__file__), "codegen", "stub_api.py")
        command = [sys.executable, path]
        self.announce(
            'Running command: %s' % str(command),
            level=distutils.log.INFO)
        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = process.communicate()
        code = process.returncode
        if code != 0:
            raise RuntimeError(f"The stubs generation failed. Output: {out}, Error: {err}")

class SDistReplace(setuptools.command.sdist.sdist):
  """Custom build command."""
  def run(self):
    self.run_command('codegen')
    super().run()



CMDCLASS_OVERRIDE.update(
    {
        "codegen": CodegenCommand,
        'sdist': SDistReplace,
    }
)

if __name__ == "__main__":
    path = os.path.join(os.path.dirname(__file__), "codegen", "stub_api.py")
    command = ['python', path]
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    process.wait()
    setuptools.setup(
        name=package_name,
        version=version,
        author="ANSYS, Inc.",
        author_email='pyansys.core@ansys.com',
        maintainer="ANSYS, Inc.",
        maintainer_email='pyansys.core@ansys.com',
        description=description,
        long_description=long_description,
        long_description_content_type='text/markdown',
        url=f"https://github.com/ansys/{package_name}",
        license="MIT",
        python_requires=">=3.9",
        install_requires=["grpcio>=1.17", "protobuf>=3.19"],
        package_dir = {"": "src"},
        packages=setuptools.find_namespace_packages("src", include=("ansys.*",)),
        package_data={
            "": ["*.proto", "*.pyi", "py.typed", "VERSION", "*.xml", "*ensight_api_test_assets.txt"],
            
        },
        entry_points={
            "ansys.tools.protoc_helper.proto_provider": [
                f"{dot_package_name}={dot_package_name}"
            ],
        },
        cmdclass=CMDCLASS_OVERRIDE,
    )
