"""Compare selected NYC ACRIS document IDs with one verified borough-block-lot.""" import argparse from datetime import date, datetime, timezone import json from pathlib import Path import re import subprocess from urllib.parse import urlencode BASE_URL = "https://data.cityofnewyork.us/resource" def read_records(dataset, document_id, fields, fixture): if fixture is not None: rows = fixture["tables"][dataset].get(document_id) if rows is None: raise SystemExit(f"The fixture has no {dataset} rows for {document_id}.") return [{field: row.get(field) for field in fields.split(",")} for row in rows], fixture["queries"][dataset] url = f"{BASE_URL}/{dataset}.json?{urlencode({'document_id': document_id})}" response = subprocess.run( ["curl", "--fail", "--silent", "--show-error", "--max-time", "15", "--retry", "2", "--retry-max-time", "25", url], capture_output=True, text=True, ) if response.returncode != 0: raise SystemExit(f"Could not retrieve {document_id} from ACRIS {dataset}. {response.stderr.strip()}") records = json.loads(response.stdout) if not isinstance(records, list) or len(records) >= 1000: raise SystemExit(f"Review the ACRIS response before using {document_id}: {url}") return [{field: row.get(field) for field in fields.split(",")} for row in records], url def review_document(document_id, parcel, cutoff, fixture): legals, legals_url = read_records( "8h5j-fqxa", document_id, "borough,block,lot,street_number,street_name,partial_lot,good_through_date", fixture, ) matches = [ row for row in legals if tuple(str(row[field]).lstrip("0") for field in ("borough", "block", "lot")) == parcel ] master, master_url = read_records( "bnx9-e6tj", document_id, "crfn,doc_type,document_date,recorded_datetime,good_through_date", fixture, ) if len(master) > 1: raise SystemExit(f"Multiple ACRIS Master rows for {document_id}. Review {master_url}") record = master[0] if master else None recorded = record["recorded_datetime"] if record else None parties, parties_url = [], None if matches and record and record["doc_type"] == "DEED": parties, parties_url = read_records( "636b-3b5g", document_id, "party_type,name,good_through_date", fixture, ) return { "document_id": document_id, "parcel_links": matches, "master": record, "recorded_by_cutoff": date.fromisoformat(recorded[:10]) <= cutoff if recorded and cutoff else None, "deed_parties": parties, "queries": {"legals": legals_url, "master": master_url, "deed_parties": parties_url}, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("bbl", help="Ten-digit NYC tax lot identifier for borough 1 through 4") parser.add_argument("document_ids", nargs="+", metavar="DOCUMENT_ID", help="Numeric ACRIS document IDs") parser.add_argument("--recorded-through", type=date.fromisoformat, metavar="YYYY-MM-DD") parser.add_argument("--fixture", type=Path, help="Replay saved records from a JSON file") args = parser.parse_args() if not re.fullmatch(r"[1-4][0-9]{9}", args.bbl): parser.error("Enter a ten-digit BBL in Manhattan, the Bronx, Brooklyn, or Queens.") document_ids = list(dict.fromkeys(args.document_ids)) if len(document_ids) > 20 or any(not re.fullmatch(r"[0-9]{16}", x) for x in document_ids): parser.error("Enter at most 20 distinct 16-digit document IDs, not CRFNs.") parcel = (args.bbl[0], args.bbl[1:6].lstrip("0"), args.bbl[6:].lstrip("0")) fixture = json.loads(args.fixture.read_text()) if args.fixture else None if fixture and fixture["bbl"] != args.bbl: parser.error(f"The fixture only covers BBL {fixture['bbl']}.") records = [review_document(document_id, parcel, args.recorded_through, fixture) for document_id in document_ids] print(json.dumps({ "bbl": args.bbl, "recorded_through": args.recorded_through.isoformat() if args.recorded_through else None, "data_mode": "fixture" if fixture else "live", "retrieved_at_utc": fixture["retrieved_at_utc"] if fixture else datetime.now(timezone.utc).isoformat(), "records": records, }, indent=2)) if __name__ == "__main__": main()