""" Variable Library Service Loads domain-aware variable definitions from data/variables/ and merges base → domain → subfield layers to produce the full field set for any domain/subfield combination. Used by Quick Create, case forms, and the explore route. Usage: from core.services.variable_library import get_variables, get_suggested_procedures fields = get_variables("surgery", "visceral") # => merged dict of base + surgery/_common + surgery/visceral case fields procedures = get_suggested_procedures("surgery", "visceral") # => ["Laparoscopic cholecystectomy", ...] """ import json from pathlib import Path from typing import Any, Dict, List, Optional import structlog logger = structlog.get_logger(__name__) _DATA_DIR = Path(__file__).parent.parent.parent.parent / "data" / "variables" # In-memory cache (populated on first call, keyed by (domain, subfield)) _cache: dict[tuple, dict[str, Any]] = {} def _load_json(path: Path) -> dict[str, Any]: """Load a JSON file, return empty dict on failure.""" if not path.exists(): return {} try: return json.loads(path.read_text(encoding="utf-8")) except Exception as e: logger.warning("Failed to load variable file %s: %s", path, e) return {} def get_variables(domain: str, subfield: str | None = None) -> dict[str, Any]: """ Return merged variable definitions for a domain/subfield. Merge order (later overrides earlier): 1. _base.json (universal fields) 2. {domain}/_common.json (domain-wide fields) 3. {domain}/{subfield}.json (specialty fields) Returns dict with keys like "case", "trace", "event" — each containing field name → definition mappings. """ cache_key = (domain, subfield) if cache_key in _cache: return _cache[cache_key] # Layer 1: Base base = _load_json(_DATA_DIR / "_base.json") # Layer 2: Domain common domain_common = _load_json(_DATA_DIR / domain / "_common.json") # Layer 3: Subfield subfield_data: dict[str, Any] = {} if subfield: subfield_data = _load_json(_DATA_DIR / domain / f"{subfield}.json") # Merge — field-level merge per form type (case, trace, event) result: dict[str, Any] = {} for form_type in ("case", "trace", "event"): merged = {} for layer in (base, domain_common, subfield_data): if form_type in layer: merged.update(layer[form_type]) if merged: result[form_type] = merged _cache[cache_key] = result return result def get_suggested_procedures(domain: str, subfield: str | None = None) -> list[str]: """Return suggested procedures/actions for a domain/subfield.""" if subfield: data = _load_json(_DATA_DIR / domain / f"{subfield}.json") if "suggested_procedures" in data: return data["suggested_procedures"] data = _load_json(_DATA_DIR / domain / "_common.json") return data.get("suggested_procedures", []) def list_domains_with_variables() -> list[str]: """List all domains that have variable definitions.""" if not _DATA_DIR.exists(): return [] return sorted(d.name for d in _DATA_DIR.iterdir() if d.is_dir() and not d.name.startswith("_")) def list_subfields_with_variables(domain: str) -> list[str]: """List all subfields that have variable definitions for a domain.""" domain_dir = _DATA_DIR / domain if not domain_dir.exists(): return [] return sorted( f.stem for f in domain_dir.glob("*.json") if f.stem != "_common" and not f.stem.startswith("_") ) def clear_cache() -> None: """Clear the variable cache (for testing or hot-reload).""" _cache.clear()