#!/usr/bin/env python3
"""Save one JSON report per CSV row. No third-party packages required.
Set PP_API_KEY in your environment, then run:
  python3 batch-example.py addresses.csv
CSV header must include: address
Each address should include street, town, NJ and ZIP when available.
Keys belong in private scripts, never public websites or source control.
"""
import csv
import json
import os
from pathlib import Path
import sys
import time
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def main():
    key = os.environ.get("PP_API_KEY")
    if not key or len(sys.argv) != 2:
        sys.exit("Set PP_API_KEY and pass the path to an addresses CSV.")
    output = Path("property-reports")
    output.mkdir(exist_ok=True)
    with open(sys.argv[1], newline="", encoding="utf-8-sig") as source:
        rows = csv.DictReader(source)
        if "address" not in (rows.fieldnames or []):
            sys.exit("CSV needs an address column.")
        for index, row in enumerate(rows, 1):
            address = row["address"].strip()
            if not address:
                continue
            target = output / f"report-{index:05d}.json"
            # Resume only when the saved result belongs to this same CSV row.
            if target.exists():
                saved = json.loads(target.read_text())
                if saved.get("input_address") == address and "report" in saved:
                    continue
            url = "https://oprasearch.app/agent/report?" + urlencode({"address": address, "format": "json"})
            for attempt in range(3):
                request = Request(url, headers={"X-API-Key": key, "User-Agent": "PermitParcel-CSV/1.0"})
                try:
                    with urlopen(request, timeout=45) as response:
                        report = json.load(response)
                    target.write_text(json.dumps({"input_address": address, "report": report}, indent=2))
                    print(f"Saved row {index}")
                    break
                except HTTPError as error:
                    try:
                        detail = json.loads(error.read())
                    except (ValueError, UnicodeDecodeError):
                        detail = {"error": {"code": "http_error", "message": f"HTTP {error.code}"}}
                    code = detail.get("error", {}).get("code")
                    if error.code in (401, 403) or code == "daily_limit":
                        sys.exit(f"Stopped at row {index}: {code or error.code}. Fix the key or wait for the UTC daily reset, then rerun to resume.")
                    if error.code in (429, 502, 503, 504) and attempt < 2:
                        try:
                            wait = max(3, min(3600, int(error.headers.get("Retry-After", "60"))))
                        except ValueError:
                            wait = 60
                        time.sleep(wait)
                        continue
                    target.write_text(json.dumps({"input_address": address, "error_response": detail}, indent=2))
                    print(f"Row {index}: HTTP {error.code}; saved error for review")
                    break
            time.sleep(2.1)  # At most 30 requests/minute, including across fast responses.


if __name__ == "__main__":
    main()
