# -*- coding: utf-8 -*-
"""merge_deal_panel.py — merge collector CSVs into one normalized ASIC deal panel; QA report.
Usage: python3 -I merge_deal_panel.py out.csv in1.csv in2.csv ...
Rules: schema-normalize; drop rows without source_url or quote; derive usd_per_th from total_usd/total_th when missing;
price_fixing_date falls back to announce_date (noted); de-duplicate by (buyer, date, model, total_th) keeping the most complete row.
"""
import csv, sys, os, datetime as dt
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import asic_deals as AD

def norm(r):
    o = {k: (r.get(k) or "").strip() if isinstance(r.get(k), str) else (r.get(k) if r.get(k) is not None else "") for k in AD.SCHEMA}
    for k in ("units", "th_per_unit", "total_th", "jth", "total_usd", "usd_per_th"):
        v = AD._num(o[k]); o[k] = "" if v is None else v
    raw_pf = str(o["price_fixing_date"]); period = None
    import re
    if re.search(r"Q[1-4]", raw_pf) or re.search(r"(?i)\bFY|year", raw_pf) or (o["seller_type"].upper() == "SELLER_ASP" and re.search(r"(?i)Q[1-4]|FY|year|quarter", str(o["delivery_period"]) + " " + raw_pf)):
        period = "year" if re.search(r"(?i)FY|year|annual", raw_pf + " " + str(o["delivery_period"])) and not re.search(r"Q[1-4]", raw_pf + " " + str(o["delivery_period"])) else "quarter"
    for k in ("announce_date", "price_fixing_date", "source_date"):
        d = AD._date(o[k]); o[k] = d.isoformat() if d else ""
    if period and o["price_fixing_date"]:   # period-average price → period midpoint
        d = dt.date.fromisoformat(o["price_fixing_date"]) - dt.timedelta(days=(182 if period == "year" else 45))
        o["price_fixing_date"] = d.isoformat(); o["notes"] = (o["notes"] + "; " if o["notes"] else "") + f"price_fixing_date set to {period} midpoint (period-average price)"
    if o["total_th"] == "" and o["units"] != "" and o["th_per_unit"] != "": o["total_th"] = o["units"] * o["th_per_unit"]
    if o["usd_per_th"] == "" and o["total_usd"] != "" and o["total_th"] not in ("", 0):
        o["usd_per_th"] = o["total_usd"] / o["total_th"]; o["price_basis"] = o["price_basis"] or "DERIVED_TOTAL_DIV_TH"
    if o["price_fixing_date"] == "" and o["announce_date"]:
        o["price_fixing_date"] = o["announce_date"]; o["notes"] = (o["notes"] + "; " if o["notes"] else "") + "price_fixing_date = announce_date (contract date not disclosed)"
    o["seller_type"] = o["seller_type"].upper() or "OEM_PRIMARY"; o["includes_non_miner"] = o["includes_non_miner"].upper() or "ND"
    o["payment_form"] = o["payment_form"].upper() or "ND"; o["confidence"] = o["confidence"].upper()[:1] or "C"
    return o

def main():
    out, ins = sys.argv[1], sys.argv[2:]
    rows = []; rejected = []
    for p in ins:
        if not os.path.exists(p): print("missing", p); continue
        with open(p, encoding="utf-8-sig", newline="") as f:
            for r in csv.DictReader(f):
                o = norm(r); o["notes"] = (o["notes"] + "; " if o["notes"] else "") + f"collector={os.path.basename(p)}"
                if not o["source_url"] or not o["quote"] or (o["usd_per_th"] == "" and o["total_usd"] == ""): rejected.append((o["deal_id"], "no url/quote/price")); continue
                rows.append(o)
    # de-dup
    seen = {}
    for o in rows:
        key = (o["buyer_ticker"], o["price_fixing_date"][:7], (o["model"] or "").lower()[:12], round(o["total_th"] or 0, -3) if isinstance(o["total_th"], float) else o["total_th"])
        score = sum(1 for k in AD.SCHEMA if o[k] not in ("", None))
        if key in seen and seen[key][0] >= score: rejected.append((o["deal_id"], f"duplicate of {seen[key][1]['deal_id']}")); continue
        seen[key] = (score, o)
    final = sorted((v[1] for v in seen.values()), key=lambda o: (o["price_fixing_date"], o["buyer_ticker"]))
    ids = {}
    for o in final:
        base = o["deal_id"] or f"{o['buyer_ticker']}-{o['price_fixing_date'].replace('-', '')}"
        n = ids.get(base, 0) + 1; ids[base] = n; o["deal_id"] = base if n == 1 else f"{base}-{n}"
    AD.write_normalized(final, out)
    print(f"merged {len(final)} rows from {len(ins)} files; rejected {len(rejected)}")
    for d, why in rejected: print("  reject", d, why)
    sample, excl, P = AD.fit_rows(final, "2026-10-15")
    print(f"in fit window: {len(sample)}; excluded: {len(excl)}")
    for r, why in excl: print("  excl", r["deal_id"], why)
    fit = AD.wls(sample, P)
    if fit: print("fit", {k: (round(v, 4) if isinstance(v, float) else v) for k, v in fit.items()})

if __name__ == "__main__": main()
