from hatchling.builders.hooks.plugin.interface import BuildHookInterface
from pathlib import Path

class CopyHostBinariesHook(BuildHookInterface):
    def initialize(self, *args, **kwargs):
        """
        Copy the host binaries from their build directory to the python package

        Runs as a part of pip install. No dependencies on any system commands (cp etc.)
        """
        host_bin_dir = Path(__file__).parent.parent / "host" / "bin"
        target_bin_dir = Path(__file__).parent / "tuning_utility" / "host_bin"
        target_bin_dir.mkdir(parents=True, exist_ok=True)
        for bin in host_bin_dir.glob("*"):
            if bin.is_file():
                source_permissions = bin.stat().st_mode
                target_bin = target_bin_dir / bin.name
                if target_bin.exists():
                    target_bin.unlink()
                target_bin.write_bytes(bin.read_bytes())
                target_bin.chmod(source_permissions)

