#!/usr/bin/env python3
"""
Generate tool_catalog.json from the @hdf5_tool registry.

Usage:
    python -m tools.generate_catalog
"""

import inspect
import json
import sys
from pathlib import Path

# Ensure the tools/h5py directory is on sys.path so bare imports (e.g. h5py_helpers) resolve
_h5py_dir = str(Path(__file__).resolve().parent / "h5py")
if _h5py_dir not in sys.path:
    sys.path.insert(0, _h5py_dir)

# Import all tool modules to populate the registry
from tools.h5py import (  # noqa: E402
    get_object_metadata,
    rechunk_dataset,
    apply_filter_dataset,
    visualize,
    read_semantic_metadata,
    write_semantic_metadata,
    collect_objects_for_smd,
    write_smd_batch,
    vectorize_semantic_metadata,
    query_semantic_metadata,
)

from tools.h5py.registry import TOOL_REGISTRY


def generate_catalog() -> dict:
    """Build catalog dict from the registry."""
    tools = []
    for func in TOOL_REGISTRY:
        meta = func._hdf5_tool_meta
        module = inspect.getmodule(func)
        module_name = module.__name__ if module else func.__module__
        # Build import path like: from tools.h5py.get_object_metadata import get_object_metadata
        import_str = f"from {module_name} import {meta['name']}"

        tools.append({
            "name": meta["name"],
            "import": import_str,
            "description": (func.__doc__ or "").strip().split("\n")[0],
            "detailed_description": _extract_detailed_description(func),
            "search_keywords": meta["keywords"],
            "category": meta["category"],
            "use_cases": meta["use_cases"],
        })

    return {
        "_generated": "Auto-generated by tools/generate_catalog.py — do not edit manually",
        "version": "1.0",
        "tools": tools,
    }


def _extract_detailed_description(func) -> str:
    """Extract the body of the docstring (everything after the first line)."""
    doc = func.__doc__ or ""
    lines = doc.strip().split("\n")
    if len(lines) <= 1:
        return ""
    # Skip first line and any blank lines after it
    body_lines = []
    started = False
    for line in lines[1:]:
        stripped = line.strip()
        if not started and not stripped:
            continue
        if stripped.startswith("Args:"):
            break
        if stripped.startswith("Parameters:"):
            break
        if stripped.startswith("Returns:"):
            break
        started = True
        body_lines.append(stripped)
    return " ".join(body_lines).strip()


def main():
    catalog = generate_catalog()
    catalog_path = Path(__file__).resolve().parent / "tool_catalog.json"
    with open(catalog_path, "w") as f:
        json.dump(catalog, f, indent=2)
        f.write("\n")
    print(f"Generated {catalog_path} with {len(catalog['tools'])} tools")


if __name__ == "__main__":
    main()
