"""content-c6153-000 — the award record behind each named de-obligation: what the contract was FOR (its own
description), its dates, its obligated vs potential value. GET /api/v2/awards/<generated_internal_id>/.
Referent check: the keyword filter matches award TEXT, so every named row has to be read before it is written down.
Read-only."""
import json
import sys
import time
import urllib.request

API = "https://api.usaspending.gov"
UA = {"User-Agent": "vibeagentmaking.com research"}


def award(gid):
    req = urllib.request.Request("%s/api/v2/awards/%s/" % (API, urllib.parse.quote(gid, safe="")), headers=UA)
    with urllib.request.urlopen(req, timeout=90) as r:
        return json.loads(r.read().decode("utf-8"))


def main():
    import urllib.parse  # noqa: F811
    verdicts = json.load(open(sys.argv[1], encoding="utf-8"))
    want = [r for r in verdicts["rows"] if r["verdict"] in ("TERMINATION", "STANDING", "OFFSET")][:int(sys.argv[2]) if len(sys.argv) > 2 else 8]
    for r in want:
        gid = r.get("generated_internal_id")
        try:
            d = award(gid)
        except Exception as e:                                        # noqa: BLE001
            print("%-12s %s: lookup failed (%s)" % (r["verdict"], r.get("Award ID"), type(e).__name__))
            continue
        lat = d.get("latest_transaction_contract_data") or {}
        print("== %-11s %14.2f  %s" % (r["verdict"], float(r["Transaction Amount"]), r.get("Award ID")))
        print("   recipient : %s" % ((d.get("recipient") or {}).get("recipient_name")))
        print("   agency    : %s / %s" % ((d.get("awarding_agency") or {}).get("toptier_agency", {}).get("name"),
                                          (d.get("awarding_agency") or {}).get("subtier_agency", {}).get("name")))
        print("   period    : %s .. %s (potential %s)" % ((d.get("period_of_performance") or {}).get("start_date"),
                                                          (d.get("period_of_performance") or {}).get("end_date"),
                                                          (d.get("period_of_performance") or {}).get("potential_end_date")))
        print("   money     : obligated %s | base+exercised %s | base+all options %s" %
              (d.get("total_obligation"), d.get("base_exercised_options"), d.get("base_and_all_options")))
        print("   naics/psc : %s | %s" % ((d.get("naics_hierarchy") or {}).get("base_code", {}).get("description"),
                                          (d.get("psc_hierarchy") or {}).get("base_code", {}).get("description")))
        print("   what for  : %s" % str(d.get("description"))[:300])
        if lat.get("reason_for_modification_description"):
            print("   last mod  : %s" % lat.get("reason_for_modification_description"))
        print()
        time.sleep(0.3)


if __name__ == "__main__":
    main()
