"""Tenant-level credibility flags derived from project external_context.""" from __future__ import annotations from typing import Any, Dict def build_credibility_flags(external_context: Dict[str, Any] | None) -> Dict[str, Any]: ctx = external_context or {} existing = ctx.get("credibility_flags") if isinstance(existing, dict) and existing: return dict(existing) reg_quality = (ctx.get("regulation_link_quality") or "unknown").lower() msp = ctx.get("msp_analysis") or {} using_real = bool( ctx.get("msp_using_real_data") or msp.get("using_real_data") or msp.get("data_source") in ("gus", "regon", "msp_live") ) grounded = bool(ctx.get("regulation_grounded") or ctx.get("precise_regulation_url")) snapshot = ctx.get("snapshot_data") or {} has_snapshot = bool(snapshot.get("key_rules") or snapshot.get("version_hash")) warnings: list[str] = [] if reg_quality in ("unknown", "listing", "low"): warnings.append("regulation_link_weak") if not using_real: warnings.append("msp_not_grounded") if not has_snapshot: warnings.append("missing_regulation_snapshot") if reg_quality == "high" and using_real and has_snapshot: level = "high" elif reg_quality in ("high", "medium") and grounded: level = "medium" else: level = "needs_attention" return { "overall_trust_level": level, "msp_using_real_data": using_real, "regulation_link_quality": reg_quality, "regulation_grounded": grounded, "has_regulation_snapshot": has_snapshot, "warnings": warnings, }