#!/usr/bin/env python3
"""Deterministic four-month water-usage trend summary.

Reads a CSV with columns: month,gallons,amount
Prints the latest usage, month-over-month change, the four-month rolling
average, a trend label, and any anomalies (usage > 1.5x rolling avg, or a
bill over $200).

Usage:
    python3 trend.py history.csv     # analyze a file
    python3 trend.py                 # run against the built-in sample
Stdlib only — no dependencies.
"""
import csv
import io
import sys

# Fallback so the script runs out of the box with no file provided.
SAMPLE_CSV = """month,gallons,amount
2025-01,3800,42.10
2025-02,3600,40.50
2025-03,4100,45.80
2025-04,5200,58.90
2025-05,8700,96.40
2025-06,14200,168.30
"""


def load(rows):
    out = []
    for r in csv.DictReader(rows):
        out.append({"month": r["month"].strip(),
                    "gallons": float(r["gallons"]),
                    "amount": float(r["amount"])})
    return out


def summarize(data):
    if not data:
        return "No rows to analyze."
    gallons = [d["gallons"] for d in data]
    window = gallons[-4:]
    rolling = sum(window) / len(window)
    latest = data[-1]
    mom = "n/a"
    if len(gallons) >= 2 and gallons[-2]:
        mom = f"{(gallons[-1] - gallons[-2]) / gallons[-2] * 100:+.1f}%"
    # Trend: compare latest to the average of the prior months in the window.
    prior = window[:-1] or window
    base = sum(prior) / len(prior)
    if latest["gallons"] > base * 1.05:
        trend = "rising"
    elif latest["gallons"] < base * 0.95:
        trend = "falling"
    else:
        trend = "steady"
    anomalies = [f"{d['month']}: {d['gallons']:.0f} gal (> 1.5x rolling avg)"
                 for d in data if d["gallons"] > rolling * 1.5]
    anomalies += [f"{d['month']}: bill ${d['amount']:.2f} (> $200)"
                  for d in data if d["amount"] > 200]
    lines = [
        f"Latest month   : {latest['month']}",
        f"Latest usage   : {latest['gallons']:.0f} gallons ({mom} vs prior month)",
        f"4-month avg    : {rolling:.0f} gallons",
        f"Trend          : {trend}",
        f"Anomalies      : {'; '.join(anomalies) if anomalies else 'none'}",
    ]
    return "\n".join(lines)


def main():
    if len(sys.argv) > 1:
        with open(sys.argv[1], newline="", encoding="utf-8") as f:
            data = load(f)
    else:
        print("(no CSV given — using built-in sample data)\n")
        data = load(io.StringIO(SAMPLE_CSV))
    print(summarize(data))


if __name__ == "__main__":
    main()
