"""Blender headless script: extract asset catalog from a .blend library file.

Usage:
    blender --background --python catalog_assets.py -- <blend_path>

Outputs a single JSON line to stdout:
    {"materials": ["Mat1", "Mat2", ...], "node_groups": ["NG1", ...]}

Only assets marked via Blender's asset system (asset_data is not None) are included.
"""
from __future__ import annotations

import json
import sys
import traceback


def main() -> None:
    argv = sys.argv
    if "--" not in argv:
        print(json.dumps({"error": "No blend path provided after --"}))
        sys.exit(1)

    blend_path = argv[argv.index("--") + 1]

    import bpy  # type: ignore[import]

    bpy.ops.wm.open_mainfile(filepath=blend_path)

    materials = [m.name for m in bpy.data.materials if m.asset_data is not None]
    node_groups = [ng.name for ng in bpy.data.node_groups if ng.asset_data is not None]

    catalog = {"materials": materials, "node_groups": node_groups}
    print(json.dumps(catalog))


try:
    main()
except SystemExit:
    raise
except Exception:
    traceback.print_exc()
    sys.exit(1)
