"""
Shared s-expression component definitions.

Loaded at app startup via ``load_shared_components()``.  Each component
is defined in an external ``.sx`` file under ``templates/``.
"""

from __future__ import annotations

import os

from .jinja_bridge import load_sx_dir, register_reload_callback, watch_sx_dir


def load_shared_components() -> None:
    """Register all shared s-expression components.

    Defers finalization (deps/hash) so the calling app can load service
    components before the single finalize pass.
    """
    # Load SX libraries first — reader macros (#z3 etc.) must resolve
    # before any .sx file that uses them is parsed
    _load_sx_libraries()
    register_reload_callback(_load_sx_libraries)

    templates_dir = os.path.join(os.path.dirname(__file__), "templates")
    load_sx_dir(templates_dir, _finalize=False)
    watch_sx_dir(templates_dir)


def _load_sx_libraries() -> None:
    """Load self-hosted SX libraries from the ref directory."""
    from .jinja_bridge import register_components
    ref_dir = os.path.join(os.path.dirname(__file__), "ref")
    for name in ("z3.sx", "prove.sx"):
        path = os.path.join(ref_dir, name)
        if os.path.exists(path):
            with open(path, encoding="utf-8") as f:
                register_components(f.read(), _defer_postprocess=True)
