"""Setup script with build hook to generate d3.py before building."""

import sys
from pathlib import Path
from setuptools import setup
from setuptools.command.build_py import build_py


class BuildWithProxy(build_py):
    """Custom build command that generates d3.py before building."""

    def run(self) -> None:
        """Run the build process with proxy generation."""
        self.generate_d3_proxy()
        super().run()

    def generate_d3_proxy(self) -> None:
        """Generate d3.py from d3.pyi stub file.

        Raises:
            FileNotFoundError: If the stub file doesn't exist
            Exception: If proxy generation fails
        """
        print("=" * 60)
        print("Pre-build hook: Generating d3.py")
        print("=" * 60)

        # Use absolute paths based on project root
        project_root = Path(__file__).parent.resolve()
        stub_path = project_root / "src" / "designer_plugin" / "pystub" / "d3.pyi"
        output_path = project_root / "src" / "designer_plugin" / "pystub" / "d3_proxy.py"
        src_path = str(project_root / "src")

        # Verify stub file exists
        if not stub_path.exists():
            error_msg = f"Stub file not found: {stub_path}"
            print(f"ERROR: {error_msg}", file=sys.stderr)
            raise FileNotFoundError(error_msg)

        # Check if output is already up-to-date (idempotency)
        if output_path.exists():
            stub_mtime = stub_path.stat().st_mtime
            output_mtime = output_path.stat().st_mtime
            if output_mtime > stub_mtime:
                print("d3.py is up to date, skipping generation")
                print("=" * 60)
                return

        # Add src to path temporarily
        sys.path.insert(0, src_path)

        try:
            # Import the generation function
            from designer_plugin.scripts.generate_proxy import generate_proxy_module

            # Generate the proxy module
            print(f"Reading stub file: {stub_path}")
            proxy_code = generate_proxy_module(str(stub_path))

            # Write to output
            print(f"Writing proxy module: {output_path}")
            output_path.write_text(proxy_code, encoding="utf-8")

            print(f"Successfully generated d3.py ({len(proxy_code.splitlines())} lines)")
            print("=" * 60)

        except Exception as e:
            error_msg = f"Failed to generate d3.py: {e}"
            print(f"ERROR: {error_msg}", file=sys.stderr)
            raise  # Re-raise to fail the build

        finally:
            # Remove from path (only if it was added)
            if src_path in sys.path:
                sys.path.remove(src_path)


if __name__ == "__main__":
    setup(
        cmdclass={
            'build_py': BuildWithProxy,
        }
    )
