#!/usr/bin/env python3
"""diskfill - estimate days until a disk fills, from recent growth snapshots.
Usage: diskfill [snapshot [MOUNT...]] [--db PATH] [--selftest]
Records used-bytes snapshots in ~/.cache/fileutils/diskfill.csv and fits a
line through them per mount: days-left = (total - used) / growth-per-day.
With no subcommand it reports the estimate for every mount it has data for."""
import argparse, csv, os, sys, time
from datetime import datetime

DEFAULT_DB = os.path.expanduser("~/.cache/fileutils/diskfill.csv")

def human(n):
    for u in ("B", "K", "M", "G", "T"):
        if abs(n) < 1024 or u == "T":
            return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
        n /= 1024.0
    return f"{n:.1f}T"

def mounts():
    out = []
    try:
        with open("/proc/mounts") as f:
            for line in f:
                parts = line.split()
                if len(parts) >= 3:
                    out.append((parts[1], parts[2]))
    except OSError:
        pass
    return out

def stat_mount(mp):
    try:
        st = os.statvfs(mp)
    except OSError:
        return None
    total = st.f_blocks * st.f_frsize
    free = st.f_bfree * st.f_frsize
    return total, total - free

def read_db(path):
    rows = []
    if not os.path.exists(path):
        return rows
    with open(path, newline="") as f:
        for row in csv.reader(f):
            if len(row) != 4:
                continue
            try:
                rows.append((float(row[0]), row[1], int(row[2]), int(row[3])))
            except ValueError:
                continue
    return rows

def snapshot(db, only=None):
    os.makedirs(os.path.dirname(db) or ".", exist_ok=True)
    now = time.time()
    new = 0
    with open(db, "a", newline="") as f:
        w = csv.writer(f)
        for mp, _fs in mounts():
            if only and mp not in only:
                continue
            s = stat_mount(mp)
            if not s or s[0] == 0:
                continue
            w.writerow([int(now), mp, s[1], s[0]])
            new += 1
    return new

def estimate(rows):
    """rows: list of (ts, mount, used, total) for one mount. Returns dict."""
    if len(rows) < 2:
        return {"status": "need-more-data", "points": len(rows)}
    rows = sorted(rows)
    total = rows[-1][3]
    used_now = rows[-1][2]
    # least-squares slope of used vs time (bytes/sec)
    n = len(rows)
    xs = [r[0] for r in rows]
    ys = [r[2] for r in rows]
    mx = sum(xs) / n
    my = sum(ys) / n
    den = sum((x - mx) ** 2 for x in xs)
    if den == 0:
        return {"status": "need-more-data", "points": n}
    slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / den
    if slope <= 0:
        return {"status": "not-growing", "points": n, "slope_day": slope * 86400}
    days = (total - used_now) / (slope * 86400)
    return {"status": "ok", "points": n, "days": days,
            "slope_day": slope * 86400, "used": used_now, "total": total,
            "fill_date": datetime.fromtimestamp(time.time() + days * 86400).strftime("%Y-%m-%d")}

def report(db):
    rows = read_db(db)
    if not rows:
        print(f"no snapshots yet in {db}")
        print("run: diskfill snapshot   (then again later - one point cannot make a line)")
        return 0
    by_mount = {}
    for r in rows:
        by_mount.setdefault(r[1], []).append(r)
    print(f"{'MOUNT':<24} {'USED':>10} {'GROWTH/DAY':>12} {'DAYS LEFT':>10}  VERDICT")
    any_alarm = False
    for mp in sorted(by_mount):
        e = estimate(by_mount[mp])
        if e["status"] == "need-more-data":
            print(f"{mp:<24} {'':>10} {'':>12} {'':>10}  need at least 2 snapshots ({e['points']} so far)")
        elif e["status"] == "not-growing":
            print(f"{mp:<24} {human(by_mount[mp][-1][2]):>10} {human(e['slope_day']):>12} {'--':>10}  not growing (stable or shrinking)")
        else:
            verdict = f"fills ~{e['fill_date']}"
            if e["days"] < 30:
                verdict += "  <-- URGENT: under 30 days"
                any_alarm = True
            elif e["days"] < 90:
                verdict += "  <-- soon: under 90 days"
            print(f"{mp:<24} {human(e['used']):>10} {human(e['slope_day']):>12} {e['days']:>10.1f}  {verdict}")
    return 1 if any_alarm else 0

def selftest():
    import tempfile
    tmp = tempfile.mkdtemp(prefix="diskfill-test-")
    db = os.path.join(tmp, "db.csv")
    now = time.time()
    total = 100 * 1024**3
    with open(db, "w", newline="") as f:
        w = csv.writer(f)
        for d, used_gb in ((10, 50), (5, 55), (0, 60)):
            w.writerow([int(now - d * 86400), "/data", used_gb * 1024**3, total])
    e = estimate(read_db(db))
    ok = True
    if e["status"] != "ok":
        print(f"FAIL: status {e['status']}"); ok = False
    elif abs(e["days"] - 40.0) > 1.0:
        print(f"FAIL: days {e['days']:.1f} != ~40"); ok = False
    elif abs(e["slope_day"] - 1024**3) > 1024**2:
        print(f"FAIL: slope {e['slope_day']} != 1GB/day"); ok = False
    # flat data must report not-growing, single point need-more-data
    if estimate([(now, "/x", 10, 100), (now + 86400, "/x", 10, 100)])["status"] != "not-growing":
        print("FAIL: flat data not 'not-growing'"); ok = False
    if estimate([(now, "/x", 10, 100)])["status"] != "need-more-data":
        print("FAIL: single point not 'need-more-data'"); ok = False
    import shutil; shutil.rmtree(tmp, ignore_errors=True)
    if ok:
        print("selftest: PASS (40.0 days at 1GB/day on synthetic snapshots)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="diskfill",
        description="Estimate days until a disk fills, from recent growth snapshots.")
    ap.add_argument("cmd", nargs="?", choices=["snapshot"],
        help="'snapshot' records current usage; no command prints estimates")
    ap.add_argument("mounts", nargs="*", help="mount points to snapshot (default: all)")
    ap.add_argument("--db", default=DEFAULT_DB, help="snapshot database (default %(default)s)")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks on synthetic data")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.cmd == "snapshot":
        n = snapshot(a.db, a.mounts or None)
        print(f"recorded {n} snapshot(s) in {a.db}")
        return 0
    return report(a.db)

if __name__ == "__main__":
    sys.exit(main())
