"""Step 2: Whatcom County tax parcels (county-wide, open REST).

Pulls (a) every residential parcel built 2014+ in the tracked cities (middle-housing universe outside Bellingham,
and address matching for Bellingham townhouse lots platted after their permit), and (b) the parcel behind every
Bellingham permit APN (older lots that got an ADU).
Output: data/raw/county_parcels.json  (keyed by prop_id)
"""
from common import arcgis_query, load, save

URL = "https://wcgis.whatcomcounty.us/arcgis/rest/services/EnterprisePublishing/WhatcomCo_Property/MapServer/1"
CITIES = ["BELLINGHAM", "FERNDALE", "BLAINE", "LYNDEN"]
FIELDS = ("prop_id,geo_id,TTRRSSXXXYYY,situs_num,situs_street_prefix,situs_street,situs_unit,situs_city,zoning,zoning_description,"
          "tax_area_description,subdv_cd,subdv_description,lot,property_use_cd,property_use_description,legal_acreage,"
          "market_land_val,market_improvement_val,market,title_owner_name_full,title_owner_add_full,title_owner_city,title_owner_state,"
          "tax_payer_name_full,tax_payer_add_full,imprv_type,yr_blt,sqft_la,Hyperlink")

if __name__ == "__main__":
    out = {}
    cities = ",".join(f"'{c}'" for c in CITIES)
    rows = arcgis_query(URL, f"situs_city IN ({cities}) AND yr_blt >= 2014 AND property_use_cd LIKE '1%'", FIELDS, geom=True)
    for r in rows:
        r["_why"] = "built2014+"
        out[r["prop_id"]] = r
    print(len(rows), "parcels built 2014+ in", CITIES)

    apns = sorted({p["SITE_APN"] for p in load("permits.json") if p.get("SITE_APN")} |
                  {p["PARENT_SITE_APN"] for p in load("permits.json") if p.get("PARENT_SITE_APN")})
    n = 0
    for i in range(0, len(apns), 150):
        chunk = ",".join(f"'{a}'" for a in apns[i:i + 150])
        for r in arcgis_query(URL, f"TTRRSSXXXYYY IN ({chunk})", FIELDS, geom=True):
            if r["prop_id"] not in out:
                r["_why"] = "permit_apn"
                out[r["prop_id"]] = r
                n += 1
    print(n, "more parcels from", len(apns), "permit APNs")
    save("county_parcels.json", list(out.values()))
    print(len(out), "parcels total")
