import yaml
from pathlib import Path
from setuptools import find_packages, setup
from setuptools.command.build import build

PACKAGE_NAME = "{{ package_name }}"


class ToolMetaCacheBuild(build):

    def run(self):
        from promptflow.client import PFClient

        pf_client = PFClient()
        tools = pf_client.tools._list_tools_in_package(PACKAGE_NAME, raise_error=False)

        # Generate tool meta catch file.
        meta_cache_file = Path(__file__).parent / PACKAGE_NAME / "yamls" / "tools_meta.yaml"
        meta_cache_file.parent.mkdir(parents=True, exist_ok=True)
        with open(meta_cache_file, "w", encoding="utf-8") as f:
            yaml.safe_dump(tools, f)
        super().run()

        # Remove temporary cache file
        meta_cache_file.unlink(missing_ok=True)
        meta_cache_file.parent.rmdir()


setup(
    name=PACKAGE_NAME,
    version="0.0.1",
    description="This is my tools package",
    packages=find_packages(),
    entry_points={
        "package_tools": ["{{ package_name }} = {{ package_name }}.utils:list_package_tools"],
    },
    install_requires=[
        "promptflow",
    ],
    package_data={PACKAGE_NAME: ["yamls/*.yaml"]},
    cmdclass={
        'build': ToolMetaCacheBuild,  # Generate tool meta cache file in package
    },
    include_package_data=True,   # This line tells setuptools to include files from MANIFEST.in
)
