#!/usr/bin/env python3
"""
Generate a static lazy registry file for frozen/bundled environments.
Run this script BEFORE building the MCP bundle (e.g., with PyInstaller or Nuitka).
It scans the source code for tools and writes a static mapping to _lazy_registry_static.py.
"""

import os
import sys
import json
from pathlib import Path

# Add src to path to import tooluniverse
src_path = Path(__file__).parent.parent
sys.path.insert(0, str(src_path))

try:
    from tooluniverse.tool_registry import build_lazy_registry
except ImportError:
    print(
        "Error: Could not import tooluniverse. Ensure you are running from the project root or src directory."
    )
    sys.exit(1)


def main():
    print("🔍 Scanning for tools using AST discovery...")

    # Build the registry using the existing AST logic
    # This requires the source files to be present (which they are, right now, before build)
    registry = build_lazy_registry()

    if not registry:
        print("⚠️  Warning: No tools discovered! The static registry will be empty.")
    else:
        print(f"✅ Discovered {len(registry)} tool classes.")

    # Generate the static file content
    output_path = Path(__file__).parent / "_lazy_registry_static.py"

    content = f'''"""
STATIC LAZY REGISTRY - GENERATED FILE
Do not edit manually. generated by generate_lazy_registry.py
This file allows lazy loading to work in frozen environments where source files are missing.
"""

# Map of tool_name -> module_name
STATIC_LAZY_REGISTRY = {json.dumps(registry, indent=4, sort_keys=True)}
'''

    print(f"💾 Writing static registry to {output_path}...")
    output_path.write_text(content, encoding="utf-8")
    print("✨ Done! You can now build the bundle.")


if __name__ == "__main__":
    main()
