"""The one Config loader, replacing four drifted copies under three names.

Mirrors the engine's semantics (digest.py ``_load_alexandria_config``): a
missing or malformed file is ``{}`` — Core falls back to defaults — plus the
CLI's legacy ``Alexandria/config.json`` fallback (scripts/config.py). Callers
that must fail loudly (the MCP server) pass ``strict=True``.
"""
import json
from pathlib import Path

_RELPATHS = ("Agent/config.json", "Alexandria/config.json")


def load_config(vault, strict: bool = False) -> dict:
    """Read the vault's Config. Lenient by default (``{}`` on missing/broken —
    engine parity); ``strict=True`` raises instead."""
    for rel in _RELPATHS:
        f = Path(vault) / rel
        if f.is_file():
            try:
                with open(f, encoding="utf-8") as fh:
                    # Returned as-is, no normalization: callers compare and
                    # fingerprint this against the raw file. Agent identity is
                    # `agent.address` with legacy `agent.name` mirrored by every
                    # WRITE path (scripts.config.normalize, run in validate());
                    # readers use an address-or-name fallback.
                    return json.load(fh)
            except (OSError, ValueError):
                if strict:
                    raise
                return {}
    if strict:
        raise FileNotFoundError(f"no Agent/config.json under {vault}")
    return {}
