"""Custom build script."""

import subprocess
from pathlib import Path

from hatchling.builders.hooks.plugin.interface import BuildHookInterface
from hatchling.metadata.plugin.interface import MetadataHookInterface


class CustomMetaDataHook(MetadataHookInterface):
    """
    Metadata hook.
    """

    def update(self, metadata: dict[str, object]) -> None:
        """
        Update metadata.

        Parameters
        ----------
        metadata
            The current metadata

        """


class CustomBuildHook(BuildHookInterface):
    """
    Custom build hook.
    """

    def initialize(
        self,
        version: str,
        build_data: dict[str, object],
    ) -> None:
        """
        Initialize the build process.

        Parameters
        ----------
        version
            The version (``standard``, ``editable``, ...)
        build_data
            The build data

        """
        super().initialize(version, build_data)
        if version == "standard" and self.target_name == "wheel":
            # Build extras
            base_path = Path(self.root)
            print("⏳ Extra packages building")
            for folder in base_path.iterdir():
                if folder.is_dir() and folder.name.startswith("extra."):
                    # Build package
                    result = subprocess.run(
                        [
                            "uv",
                            "build",
                            folder,
                            "--out-dir",
                            Path(self.directory, "extras"),
                            "--wheel",
                        ],
                        capture_output=True,
                        check=True,
                        text=True,
                    )
                    extra = folder.name.split(".")[-1]
                    self.metadata.core.optional_dependencies[extra] = [
                        f"{self.metadata.name}.{extra}=={self.metadata.version}",
                    ]
            print("✅ Extra packages built")
            print("⏳ Store package building")
            # Build store
            store_path = Path(self.root, "package.store")
            if store_path.exists():
                # Build package
                result = subprocess.run(
                    [
                        "uv",
                        "build",
                        store_path,
                        "--out-dir",
                        Path(self.directory, "store"),
                        "--wheel",
                    ],
                    capture_output=True,
                    check=True,
                    text=True,
                )
            print("✅ Store package built")
