import sys
import shutil
import os
from Cython.Build import cythonize
from setuptools import setup
from setuptools.extension import Extension


def copyfile(src, dst):
    if not src.lower().endswith('.py'):
        try:
            shutil.copyfile(src, dst, follow_symlinks=True)
        except shutil.SameFileError:
            pass
        return
    with open(src, 'r', encoding='utf8') as inf, open(dst, 'w', encoding='utf8') as outf:
        for line in inf.readlines():
            if line.startswith('from lc18report_dev'):
                outf.write(line.replace(
                    'from lc18report_dev', 'from lc18report'))
                continue
            outf.write(line)


def copy_src():
    root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'src')
    src_dir = os.path.join(root_dir, 'lc18report_dev')
    dst_dir = os.path.join(root_dir, 'lc18report')
    os.makedirs(dst_dir, exist_ok=True)

    for root, subdirs, files in os.walk(src_dir):
        dst_root = root.replace(src_dir, dst_dir)
        for subdir in subdirs:
            dst_subdir = os.path.join(dst_root, subdir)
            os.makedirs(dst_subdir, exist_ok=True)
        for file in files:
            file_dst = file
            need_compile = file.endswith('.py') and file != '__init__.py'
            if need_compile:
                file_dst = file.replace('.py', '.pyx')
            src = os.path.join(root, file)
            dst = os.path.join(dst_root, file_dst)
            copyfile(src, dst)

def clean_up():
    root_dir = os.path.dirname(os.path.abspath(__file__))
    src_dir = os.path.join(root_dir, 'src', 'lc18report')
    build_dir = os.path.join(root_dir, 'build')
    egg_info_dir = os.path.join(root_dir, 'lc18report.egg-info')
    shutil.rmtree(src_dir, ignore_errors=True)
    shutil.rmtree(build_dir, ignore_errors=True)
    shutil.rmtree(egg_info_dir, ignore_errors=True)


copy_src()

setup(
    name='lc18report',
    version='0.7.21',
    description='Reporting Program for CarrierGene Lung Cancer 18-gene panel',
    author='CarrierGene.IVDg',
    author_email='rui.li@nuprobe.com',
    packages=['lc18report'],
    package_dir={'lc18report': 'src/lc18report'},
    package_data={
        'lc18report': [
            'template/report_template_v*.conf',
            'template/report_template_v*.docx',
            'template/yuedong_template_v*.conf',
            'template/yuedong_template_v*.docx',
        ],
    },
    install_requires=[
        'pycryptodomex>=3.11.0',
        'python-docx>=0.8.11',
        'pandas>=1.3.1',
        'PyYAML>=5.4.1',
        'openpyxl>=3.0.7',
        'xlrd>=2.0.1',
        'packaging>=21.3',
        'matplotlib>=3.5.1',
    ],
    python_requires='>=3.6',
    entry_points='''
        [console_scripts]
        lc18=lc18report.main:main
    ''',
    ext_modules=cythonize(
        [Extension("lc18report.*", ["src/lc18report/*.pyx"])],
        language_level="3"
    ),
)

clean_up()
