"""
模板 registry 摘要导出器 - 把 ``@ab-templates/metadata`` 的 registry.json
浓缩为 LLM prompt / 离线脚本使用的精简版本并写盘。

历史：本模块之前还托管了 ``bind_template`` / ``load_template`` / ``extract_props``
等 DSL→TemplateBinding 接口；那条路径已被 ``scripts/match_template.py`` 接管
(由 render-video 直接 import)，留在这里的副本无任何外部调用方且与
match_template 的算法已经漂移。删除这些死接口后，本文件只保留 ``sync_registry``
所需的最小依赖链 (``_load_registry`` → ``load_all_templates`` → ``build_registry``)。

monorepo 路径解析统一走 ``scripts/template_paths``，避免本文件再自己数 ``..``。
"""

from __future__ import annotations

import json
import os
import sys
from typing import Optional

# template_paths 住在 ../../scripts/，把它挂上 sys.path 后才能 import。
_SCRIPTS_DIR = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "..", "..", "scripts")
)
if _SCRIPTS_DIR not in sys.path:
    sys.path.insert(0, _SCRIPTS_DIR)

from template_paths import monorepo_registry_path  # noqa: E402

_registry_cache: Optional[dict] = None


def _load_registry(registry_path: Optional[str] = None) -> dict:
    """Load and cache the template registry from ``@ab-templates/metadata``.

    File-only: this helper never goes to HTTP (that's ``registry_loader`` 的
    职责)；``sync_registry`` 的输出只是给 LLM prompt 用，对一致性要求弱，所以
    本地读盘即可。
    """
    global _registry_cache
    if _registry_cache is not None:
        return _registry_cache

    path = registry_path or monorepo_registry_path()
    if not os.path.isfile(path):
        return {"templates": []}

    with open(path, "r", encoding="utf-8") as f:
        _registry_cache = json.load(f)
    return _registry_cache


def load_all_templates(registry_path: Optional[str] = None) -> list[dict]:
    """Return every template definition from the metadata registry."""
    registry = _load_registry(registry_path)
    return registry.get("templates", [])


def build_registry(registry_path: Optional[str] = None) -> dict:
    """Return the registry in the legacy summary format (for LLM prompts etc.)."""
    templates = load_all_templates(registry_path)
    matching_fields = [
        "templateId", "name", "description", "supportedAspectRatios",
        "supportedDurations", "styleTags", "scenePatterns", "assetRequirements",
    ]
    summary = []
    for tpl in templates:
        summary.append({k: tpl[k] for k in matching_fields if k in tpl})
    return {
        "version": "v1alpha1",
        "description": "视频模板注册表 - 来自 @ab-templates/metadata",
        "templates": summary,
    }


def sync_registry(output_path: Optional[str] = None, registry_path: Optional[str] = None) -> str:
    """Write a local registry-cache.json from ``@ab-templates/metadata``.

    Returns the absolute path of the written file.
    """
    registry = build_registry(registry_path)
    out = output_path or os.path.join(os.path.dirname(__file__), "..", "registry-cache.json")
    out = os.path.abspath(out)
    with open(out, "w", encoding="utf-8") as f:
        json.dump(registry, f, ensure_ascii=False, indent=2)
        f.write("\n")
    return out
