"""Compare monthly asking rent to Zillow's rent estimate in an enriched snapshot.

Usage: python compare_rents.py output/properties.json > rent-comparison.csv
No API calls. Excluded rows remain in the report with an explicit reason.
"""
import csv
import json
import sys
from decimal import Decimal, InvalidOperation
from pathlib import Path


def positive(value):
    if value is None or isinstance(value, bool):
        return None
    try:
        number = Decimal(str(value))
        return number if number.is_finite() and number > 0 else None
    except InvalidOperation:
        return None


def compare(row):
    result = {"input_id": row.get("input_id"), "address": row.get("address"),
              "fetched_at": row.get("fetched_at"), "asking_rent_usd": None,
              "rent_estimate_usd": None, "gap_usd": None, "gap_pct": None, "reason": ""}
    if row.get("status") != "ok":
        result["reason"] = "lookup_not_successful"
    elif row.get("review_required") is not False:
        result["reason"] = "identity_needs_review"
    elif row.get("home_status") != "FOR_RENT":
        result["reason"] = "not_current_rental"
    elif row.get("currency") != "USD":
        result["reason"] = "currency_not_usd"
    else:
        asking, estimate = positive(row.get("price")), positive(row.get("rent_zestimate"))
        if asking is None or estimate is None:
            result["reason"] = "missing_or_nonpositive_rent"
        else:
            gap = asking - estimate
            result.update(asking_rent_usd=asking, rent_estimate_usd=estimate,
                          gap_usd=gap, gap_pct=(gap / estimate * 100).quantize(Decimal("0.01")),
                          reason="compare_after_unit_and_lease_review")
    return result


def spreadsheet_cell(value):
    if isinstance(value, str) and (value.lstrip().startswith(("=", "+", "-", "@"))
                                  or value.startswith(("\t", "\r", "\n"))):
        return "'" + value
    return value


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python compare_rents.py output/properties.json > rent-comparison.csv")
    snapshot = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
    fields = list(compare({}))
    writer = csv.DictWriter(sys.stdout, fieldnames=fields)
    writer.writeheader()
    for row in snapshot["rows"]:
        writer.writerow({k: spreadsheet_cell(v) for k, v in compare(row).items()})
