from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
from setuptools.command.install import install
import compileall
import os
import sys
import shutil
from pathlib import Path

compileDirs=['utils']

class CustomBuildPy(build_py):
    def run(self):
        # 获取当前 Python 版本信息
        py_version = f".cpython-{sys.version_info.major}{sys.version_info.minor}"

        for dir in compileDirs:
            for root,_,subFiles in os.walk(dir):
                compileall.compile_dir(root, force=True)

                for file in subFiles:
                    if file.endswith('.pyc'):
                        pyc_path = os.path.join(root, file)
                        new_File = file.replace(py_version, '')
                        new_path=os.path.join(Path(root).parent,new_File)
                        shutil.move(pyc_path, new_path)

        super().run()

class InstallCommand(install):
    def run(self):
        super().run()
        # Remove all .py files from the installed package
        # 若用于开发，可查看导入的自定义package 则注释本代码段
        # 若用于部署交付，可应用本代码
        # for root, _, files in os.walk(self.install_lib):
        #     for file in files:
        #         if file.endswith('.py'):
        #             os.remove(os.path.join(root, file))

setup(
    name='repositoryZN',
    version='1.2.202505131440',
    description='Repository Package', # 描述信息
    author='Xie Zhou Yang', # 作者
    packages=find_packages(),
    cmdclass={
        'build_py': CustomBuildPy,
        'install': InstallCommand,
    },
    package_data={
        'utils': ['*.pyc'],
        'utils.minioUtil': ['*.pyc'],
        'utils.rdbmsUtil': ['*.pyc']
    },
    exclude_package_data={'': ['*.py']}
)

# 获取 setup.py 所在的绝对路径
setup_dir = os.path.abspath(os.path.dirname(__file__))
# 编译打包后，删除pyc后缀文件
for root, _, files in os.walk(setup_dir):
    for file in files:
        if file.endswith('.pyc') or file.endswith('.c'):
            print(os.path.join(root, file))
            os.remove(os.path.join(root, file))
