#!/usr/bin/env python3
"""Recompute the Aerial Economy Large Drone Index level history from raw FAA registry files and compare it to the published file.

Method v2.0. One file at a time, nothing is cached between days, nothing is read from our earlier results.
For each published day:
  1. get the raw MASTER file named in that day's receipt (our own capture, the public archive copy of the same FAA file, or a year-end file),
  2. check its SHA-256 against the hash recorded when it was stored,
  3. count rows whose STATUS CODE is V, T or M and whose trimmed MFR MDL CODE is in the taxonomy with one of five drone categories,
  4. level = count / base count x 100, rounded to one decimal. The base count is read from the published file (v2.0: 2,536).
Then compare every count and every level with levels.json, and write the result.

Usage: recompute_index.py levels.json taxonomy.csv result.json [--only YYYY-MM-DD ...]
  taxonomy.csv has two columns, code,category (the taxonomy a0c0a3122a58 table).
Raw files are read with rclone from the remote r2:terminal-captures (our own store). Needs: python3, duckdb, rclone.
"""
import csv, gzip, hashlib, json, os, shutil, subprocess, sys, tempfile
import duckdb

R2 = "r2:terminal-captures"
DRONES = ("agricultural_drone", "delivery_drone", "defense_drone", "inspection_drone", "entertainment_drone")


def run(*a):
    return subprocess.run(a, capture_output=True, text=True, check=True).stdout


def sha(path, gz=False):
    h = hashlib.sha256()
    with (gzip.open(path, "rb") if gz else open(path, "rb")) as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def main():
    levels_path, tax_path, out_path = sys.argv[1:4]
    only = sys.argv[5:] if len(sys.argv) > 5 and sys.argv[4] == "--only" else None
    data = json.load(open(levels_path))
    days = data["levels"]
    base = data["base_count"]
    con = duckdb.connect()
    con.execute("create table cat(code varchar, category varchar)")
    con.executemany("insert into cat values (?,?)", [tuple(r[:2]) for r in csv.reader(open(tax_path)) if r and r[0] != "code"])
    d_sql = ",".join(f"'{c}'" for c in DRONES)
    res, bad = [], 0
    for row in days:
        d = row["date"]
        if only and d not in only:
            continue
        tmp = tempfile.mkdtemp()
        try:
            if row["source"] == "r2_capture":
                run("rclone", "copy", f"{R2}/registry/{d}", tmp, "--include", "MASTER.txt.gz", "--include", "SHA256SUMS.txt")
                f = os.path.join(tmp, "MASTER.txt.gz"); got = sha(f, gz=True)
                clean = os.path.join(tmp, "m.csv")
                with gzip.open(f, "rt", encoding="utf-8-sig", newline="") as i, open(clean, "w", encoding="utf-8", newline="") as o:
                    h = i.readline(); o.write(h); w = h.count(",")
                    for ln in i:
                        if ln.strip() and ln.count(",") == w:
                            o.write(ln)
                view = f"select * from read_csv('{clean}', all_varchar=true, header=true)"
            elif row["source"] == "backfill_yearly":
                run("rclone", "copy", f"{R2}/backfill/registry/yearly/{row['yearly']}", tmp, "--include", "MASTER.parquet", "--include", "SHA256SUMS.txt")
                f = os.path.join(tmp, "MASTER.parquet"); got = sha(f)
                view = f"select * from read_parquet('{f}')"
            else:
                run("rclone", "copy", f"{R2}/backfill/registry/{d}", tmp, "--include", "MASTER.parquet", "--include", "SHA256SUMS.txt")
                f = os.path.join(tmp, "MASTER.parquet"); got = sha(f)
                view = f"select * from read_parquet('{f}')"
            n = con.execute(f"""select count(*) from (select trim("MFR MDL CODE") code, trim("STATUS CODE") st from ({view})) m
                                join cat using(code) where st in ('V','T','M') and category in ({d_sql})""").fetchone()[0]
            lvl = round(n / base * 100, 1)
            ok = n == row["count"] and lvl == row["level"] and got == row["file_sha256"]
        except Exception as e:  # noqa
            n, lvl, got, ok = None, None, None, False
        bad += 0 if ok else 1
        res.append({"date": d, "published_count": row["count"], "recomputed_count": n, "published_level": row["level"], "recomputed_level": lvl,
                    "file_sha256_matches": got == row["file_sha256"], "match": ok})
        print(d, row["count"], n, "OK" if ok else "MISMATCH", flush=True)
        shutil.rmtree(tmp, ignore_errors=True)
    out = {"days_checked": len(res), "days_matching": len(res) - bad, "days_not_matching": bad, "results": res}
    json.dump(out, open(out_path, "w"), indent=1)
    print(f"checked {len(res)}, matching {len(res) - bad}, not matching {bad}")


if __name__ == "__main__":
    main()
