"""Owner portfolios: groups every parcel an owner holds into one row with property count, cities and total assessed value.""" from collections import Counter, defaultdict from .classify import TRUST_RE, classify, group_key, norm_display COMPANY_COLS = ["name", "tier", "total_parcels", "cities", "n_cities", "total_assessed_value", "mailing_address", "mailing_city", "mailing_state", "mailing_zip", "name_variants"] def best_form(forms): """Most common original spelling; ties -> longest then alphabetical.""" m = max(forms.values()) return sorted([f for f, n in forms.items() if n == m], key=lambda x: (-len(x), x))[0] def mode_or_blank(counter): return counter.most_common(1)[0][0] if counter else "" def build_portfolios(parcels, city_order=None): """Aggregate parcel rows into one portfolio per owner, largest first. ``parcels`` yields dicts with the normalized parcel columns: city, parcel_id, owner_name, total_value, mailing_address, mailing_city, mailing_state, mailing_zip. Returns ``(rows, trust_rows)``: trusts are quarantined to their own list instead of deleted, so the decision stays auditable and a trust that is really an operating company can be rescued on review. """ combined = defaultdict(lambda: {"parcels": 0, "forms": Counter(), "cities": Counter(), "value": 0, "has_value": False, "mail": Counter()}) seen = set() for r in parcels: pid = (r.get("city", ""), r.get("parcel_id", "")) # dedupe: address points and view-join fan-out repeat a parcel id if pid[1] and pid in seen: continue if pid[1]: seen.add(pid) owner = r.get("owner_name", "") if not owner.strip(): continue up = norm_display(owner).upper() key = group_key(up) bucket = combined[key] bucket["parcels"] += 1 bucket["forms"][up] += 1 tv = r.get("total_value", "") if tv != "": bucket["value"] += int(float(tv)) bucket["has_value"] = True mail = (r.get("mailing_address", ""), r.get("mailing_city", ""), r.get("mailing_state", ""), r.get("mailing_zip", "")) if any(mail): bucket["mail"][mail] += 1 bucket["cities"][r.get("city", "")] += 1 order = list(city_order or []) rows = [] for key, v in combined.items(): mail = mode_or_blank(v["mail"]) or ("", "", "", "") cities = [c for c in order if c in v["cities"]] + sorted(c for c in v["cities"] if c not in order) rows.append({ "name": best_form(v["forms"]), "tier": classify(key), "total_parcels": v["parcels"], "cities": " ".join(f"{c}:{v['cities'][c]}" for c in cities), "n_cities": len(v["cities"]), "total_assessed_value": str(v["value"]) if v["has_value"] else "", "mailing_address": mail[0], "mailing_city": mail[1], "mailing_state": mail[2], "mailing_zip": mail[3], "name_variants": len(v["forms"]), "_key": key, }) rows.sort(key=lambda r: (-r["total_parcels"], r["name"])) is_trust = lambda r: (r["tier"] == "TRUST" or bool(TRUST_RE.search(r["name"].upper()))) trust_rows = [r for r in rows if is_trust(r)] rows = [r for r in rows if not is_trust(r)] return rows, trust_rows