"""Narrow, sanitized company context discovery.""" def collect_company_context(reader): """Read only the catalog-approved company UF/regime projection; never CNPJ.""" method = getattr(reader, "company_context_rows", None) if not callable(method): raise TypeError("reader must expose company_context_rows") rows = method() if not isinstance(rows, list) or not rows or any(not isinstance(row, dict) for row in rows): raise ValueError("company context is unavailable") ufs = {str(row.get("UF", "")).strip().upper() for row in rows} regimes = {str(row.get("REGIME", "")).strip() for row in rows} if len(ufs) != 1 or len(regimes) != 1 or not next(iter(ufs)) or not next(iter(regimes)): raise ValueError("company context is ambiguous") return {"uf": next(iter(ufs)), "regime": next(iter(regimes)), "cnpj": "REDACTED", "record_count": len(rows)}