"""Data preparation with pandas: quality-checked raw tables -> Power BI-ready star schema.

Run:  python analytics/prepare_data.py        (requires pandas)

Outputs
  analytics/data/powerbi/dim_*.csv, fact_*.csv   import these into Power BI (see docs/POWERBI_GUIDE.md)
  analytics/output/metrics_snapshot.json         KPIs recomputed here, independently of the website
  analytics/output/trend_analysis.md             trend and anomaly notes

The metric definitions are re-implemented here on purpose rather than imported from the
website. tests/reconcile.test.js then asserts that this pandas implementation and the
JavaScript engine produce identical numbers from the same raw records.
"""
import json
from pathlib import Path

import pandas as pd

ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "analytics" / "data" / "raw"
OUT = ROOT / "analytics" / "data" / "powerbi"
REPORT = ROOT / "analytics" / "output"
TIERS = ["Low", "Moderate", "High", "Critical"]
LOOKBACK_DAYS = 210


def load():
    tables = {p.stem: pd.read_csv(p, dtype=str, keep_default_na=False) for p in sorted(RAW.glob("*.csv"))}
    for col in [c for c in tables["ai_systems"].columns if c.startswith("f_")] + ["customer_facing"]:
        tables["ai_systems"][col] = tables["ai_systems"][col].astype(int)
    tables["controls"]["is_critical"] = tables["controls"]["is_critical"].astype(int)
    tables["model_changes"]["reassessment_required"] = tables["model_changes"]["reassessment_required"].astype(int)
    tables["incidents"]["customer_impact"] = tables["incidents"]["customer_impact"].astype(int)
    for col in ["sequence_in_day", "amount_usd", "prior_refunds_today_usd", "supervisor_reviewed"]:
        tables["incident_refunds"][col] = tables["incident_refunds"][col].astype(int)
    return tables


def shift(iso, days):
    return (pd.Timestamp(iso) + pd.Timedelta(days=days)).date().isoformat()


def state_at(t, as_of):
    """One row per live system with coverage, effectiveness, evidence and residual tier as of a date."""
    s = t["ai_systems"]
    live = s[(s.production_date != "") & (s.production_date <= as_of) & ~((s.retired_date != "") & (s.retired_date <= as_of))]
    sc = t["system_controls"].merge(live[["system_id"]], on="system_id").merge(t["controls"][["control_id", "is_critical"]], on="control_id")
    sc["implemented"] = (sc.implemented_date != "") & (sc.implemented_date <= as_of)

    tests = t["control_tests"]
    window = tests[(tests.test_date <= as_of) & (tests.test_date > shift(as_of, -LOOKBACK_DAYS))]
    latest = window.sort_values(["test_date", "test_id"]).groupby(["system_id", "control_id"], as_index=False).last()
    sc = sc.merge(latest[["system_id", "control_id", "result"]], on=["system_id", "control_id"], how="left")
    sc["effective"] = sc.result == "Pass"
    sc["critical_failing"] = (sc.is_critical == 1) & (sc.result == "Fail")

    ev = t["evidence"]
    current = ev[(ev.collected_date <= as_of) & (ev.valid_until > as_of)][["system_id", "control_id"]].drop_duplicates().assign(evidence_current=True)
    sc = sc.merge(current, on=["system_id", "control_id"], how="left")
    sc["evidence_current"] = sc.evidence_current.fillna(False).astype(bool)

    per = sc.groupby("system_id").agg(required=("control_id", "count"), implemented=("implemented", "sum"), effective=("effective", "sum"),
                                      evidence_current=("evidence_current", "sum"), critical_failing=("critical_failing", "sum")).reset_index()
    f = t["findings"]
    open_f = f[(f.opened_date <= as_of) & ~((f.closed_date != "") & (f.closed_date <= as_of))]
    counts = open_f.groupby("system_id").agg(open_findings=("finding_id", "count"),
                                             open_critical=("severity", lambda x: (x == "Critical").sum()),
                                             open_high=("severity", lambda x: (x == "High").sum())).reset_index()
    per = live[["system_id", "inherent_tier", "bu_id"]].merge(per, on="system_id", how="left").merge(counts, on="system_id", how="left").fillna(0)
    for col in ["required", "implemented", "effective", "evidence_current", "critical_failing", "open_findings", "open_critical", "open_high"]:
        per[col] = per[col].astype(int)

    def residual(row):
        index = TIERS.index(row.inherent_tier)
        coverage = row.implemented / row.required if row.required else 0
        effectiveness = row.effective / row.required if row.required else 0
        currency = row.evidence_current / row.required if row.required else 0
        reduction = 0
        if coverage >= 0.9 and effectiveness >= 0.8 and row.open_critical == 0 and row.open_high == 0 and row.critical_failing == 0:
            reduction = 2 if (effectiveness >= 0.95 and currency >= 0.9) else 1
            if index == 3:
                reduction = 1
        return TIERS[max(0, index - reduction)]

    per["residual_tier"] = per.apply(residual, axis=1) if len(per) else []
    per["as_of"] = as_of
    return per


def month_ends(start, end):
    return [d.date().isoformat() for d in pd.date_range(start, end, freq="ME")]


def snapshot(t, meta):
    as_of = meta["as_of"]
    now = state_at(t, as_of)
    s = t["ai_systems"]
    f = t["findings"]
    live_ids = set(now.system_id)
    open_f = f[(f.opened_date <= as_of) & ~((f.closed_date != "") & (f.closed_date <= as_of)) & f.system_id.isin(live_ids)]
    exc = t["exceptions"]
    exc = exc[(exc.granted_date <= as_of) & ~((exc.closed_date != "") & (exc.closed_date <= as_of)) & exc.system_id.isin(live_ids)]
    mc = t["model_changes"]
    pend = mc[(mc.reassessment_required == 1) & (mc.change_date <= as_of) & ~((mc.reassessment_completed_date != "") & (mc.reassessment_completed_date <= as_of)) & mc.system_id.isin(live_ids)]
    live = s[s.system_id.isin(live_ids)]
    agents = live[(live.f_autonomy >= 2) & live.inherent_tier.isin(["High", "Critical"])]
    in_scope = s[(s.registered_date <= as_of) & ~((s.retired_date != "") & (s.retired_date <= as_of))]
    kpis = {
        "in_scope": int(len(in_scope)), "live": int(len(now)),
        "required": int(now.required.sum()), "implemented": int(now.implemented.sum()),
        "effective": int(now.effective.sum()), "evidence_current": int(now.evidence_current.sum()),
        "open_findings": int(len(open_f)), "open_critical": int((open_f.severity == "Critical").sum()),
        "overdue_findings": int((open_f.due_date < as_of).sum()),
        "overdue_reviews": int(((live.next_review_date != "") & (live.next_review_date < as_of)).sum()),
        "active_exceptions": int((exc.expiry_date > as_of).sum()), "expired_exceptions": int((exc.expiry_date <= as_of).sum()),
        "pending_reassessments": int(len(pend)), "overdue_reassessments": int((pend.reassessment_due_date < as_of).sum()),
        "high_risk_agents": int(len(agents)),
        "inherent": {k: int((now.inherent_tier == k).sum()) for k in TIERS},
        "residual": {k: int((now.residual_tier == k).sum()) for k in TIERS},
    }
    monthly, facts = [], []
    tests, inc = t["control_tests"], t["incidents"]
    for end in month_ends(meta["window_start"], as_of):
        ym, st = end[:7], state_at(t, end)
        mt = tests[tests.test_date.str.startswith(ym)]
        monthly.append({
            "month": ym, "live": int(len(st)), "tests_run": int(len(mt)), "tests_passed": int((mt.result == "Pass").sum()),
            "incidents": int(inc.detected_date.str.startswith(ym).sum()), "open_critical": int(st.open_critical.sum()),
            "open_findings": int(st.open_findings.sum()), "required": int(st.required.sum()), "effective": int(st.effective.sum()),
            "evidence_current": int(st.evidence_current.sum()), "residual": {k: int((st.residual_tier == k).sum()) for k in TIERS}})
        facts.append(st)
    return {"as_of": as_of, "kpis": kpis, "monthly": monthly}, pd.concat(facts, ignore_index=True)


def star_schema(t, meta, fact_month):
    as_of = meta["as_of"]
    OUT.mkdir(parents=True, exist_ok=True)
    s = (t["ai_systems"].merge(t["business_units"], on="bu_id").merge(t["owners"].drop(columns="bu_id"), on="owner_id").merge(t["models"], on="model_id"))
    s["is_live"] = ((s.production_date != "") & (s.retired_date == "")).astype(int)
    s["is_high_risk_agent"] = ((s.f_autonomy >= 2) & s.inherent_tier.isin(["High", "Critical"])).astype(int)
    s["review_overdue"] = ((s.next_review_date != "") & (s.next_review_date < as_of) & (s.is_live == 1)).astype(int)
    s["tier_sort"] = s.inherent_tier.map(TIERS.index)
    s.to_csv(OUT / "dim_system.csv", index=False)
    t["controls"].to_csv(OUT / "dim_control.csv", index=False)
    dates = pd.DataFrame({"date": pd.date_range(meta["history_start"], "2026-12-31")})
    dates["year"], dates["month_number"] = dates.date.dt.year, dates.date.dt.month
    dates["month"], dates["month_label"] = dates.date.dt.strftime("%Y-%m"), dates.date.dt.strftime("%b %Y")
    dates["quarter"] = "Q" + dates.date.dt.quarter.astype(str) + " " + dates.year.astype(str)
    dates["in_reporting_window"] = ((dates.date >= meta["window_start"]) & (dates.date <= as_of)).astype(int)
    dates["date"] = dates.date.dt.date
    dates.to_csv(OUT / "dim_date.csv", index=False)

    tests = t["control_tests"].copy()
    tests["passed"] = (tests.result == "Pass").astype(int)
    tests.to_csv(OUT / "fact_control_tests.csv", index=False)

    f = t["findings"].copy()
    f["is_open"] = (f.closed_date == "").astype(int)
    end = f.closed_date.where(f.closed_date != "", as_of)
    f["age_days"] = (pd.to_datetime(end) - pd.to_datetime(f.opened_date)).dt.days
    f["is_overdue"] = ((f.is_open == 1) & (f.due_date < as_of)).astype(int)
    f["closed_within_sla"] = ((f.closed_date != "") & (f.closed_date <= f.due_date)).astype(int)
    f["aging_bucket"] = pd.cut(f.age_days, [-1, 30, 60, 90, 10_000], labels=["0-30", "31-60", "61-90", "90+"]).astype(str)
    f.to_csv(OUT / "fact_findings.csv", index=False)
    t["remediation_actions"].to_csv(OUT / "fact_remediation_actions.csv", index=False)

    ev = t["evidence"].copy()
    ev["is_current"] = ((ev.collected_date <= as_of) & (ev.valid_until > as_of)).astype(int)
    ev.to_csv(OUT / "fact_evidence.csv", index=False)

    e = t["exceptions"].copy()
    e["status"] = "Active"
    e.loc[e.expiry_date <= as_of, "status"] = "Expired, not closed"
    e.loc[e.closed_date != "", "status"] = "Closed"
    e.to_csv(OUT / "fact_exceptions.csv", index=False)
    t["incidents"].to_csv(OUT / "fact_incidents.csv", index=False)
    t["incident_refunds"].to_csv(OUT / "fact_incident_refunds.csv", index=False)

    mc = t["model_changes"].copy()
    mc["status"] = "Not required"
    mc.loc[mc.reassessment_required == 1, "status"] = "Pending"
    mc.loc[(mc.reassessment_required == 1) & (mc.reassessment_completed_date == "") & (mc.reassessment_due_date < as_of), "status"] = "Overdue"
    mc.loc[mc.reassessment_completed_date != "", "status"] = "Completed"
    mc.to_csv(OUT / "fact_model_changes.csv", index=False)

    fact_month.rename(columns={"as_of": "month_end"}).to_csv(OUT / "fact_system_month.csv", index=False)
    t["system_controls"].to_csv(OUT / "bridge_system_control.csv", index=False)


def trend_report(snap):
    m = pd.DataFrame(snap["monthly"])
    m["pass_rate"] = m.tests_passed / m.tests_run
    m["effectiveness"] = m.effective / m.required
    lines = ["# Trend and anomaly notes", "",
             f"Generated by `analytics/prepare_data.py` from the synthetic dataset as of {snap['as_of']}. "
             "Synthetic data: the observations below describe the generated dataset, not a real organization.", "",
             "| Month | Live systems | Tests run | Pass rate | Incidents | Open findings | Open critical | Control effectiveness |",
             "|---|---|---|---|---|---|---|---|"]
    for r in m.itertuples():
        lines.append(f"| {r.month} | {r.live} | {r.tests_run} | {r.pass_rate:.1%} | {r.incidents} | {r.open_findings} | {r.open_critical} | {r.effectiveness:.1%} |")
    lines += ["", "## Anomaly screen", "",
              "Method: for each month, compare the value with the mean and population standard deviation of all prior months "
              "(minimum four prior points). Flag when the absolute z-score is 2 or more. This is a transparent screen for "
              "review, not a forecast, and twelve points is a small sample.", ""]
    flagged = False
    for key, label in [("incidents", "Incidents"), ("pass_rate", "Test pass rate"), ("open_critical", "Open critical findings")]:
        for i in range(4, len(m)):
            prior, value = m[key].iloc[:i], m[key].iloc[i]
            sd = prior.std(ddof=0)
            if sd and abs((value - prior.mean()) / sd) >= 2:
                flagged = True
                shown = f"{value:.1%}" if key == "pass_rate" else f"{value:g}"
                lines.append(f"- **{label}, {m.month.iloc[i]}**: {shown} against a prior mean of "
                             f"{prior.mean():.2f} (z = {(value - prior.mean()) / sd:+.1f}).")
    if not flagged:
        lines.append("- No month exceeded the threshold.")
    half = len(m) // 2
    lines += ["", "## First half against second half", "",
              f"- Mean monthly incidents: {m.incidents.iloc[:half].mean():.1f} then {m.incidents.iloc[half:].mean():.1f}.",
              f"- Pooled test pass rate: {m.tests_passed.iloc[:half].sum() / m.tests_run.iloc[:half].sum():.1%} then "
              f"{m.tests_passed.iloc[half:].sum() / m.tests_run.iloc[half:].sum():.1%}.", "",
              "The September and October rise in incidents coincides with two generated events: the provider's major model "
              "version change on 2026-09-01 and incident INC-0031 on the Refund Resolution Agent. Coincidence in a synthetic "
              "dataset demonstrates the analysis pattern only; in a client setting the next step is to test the association "
              "by segmenting incidents by model and change date."]
    REPORT.mkdir(parents=True, exist_ok=True)
    (REPORT / "trend_analysis.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


if __name__ == "__main__":
    meta = json.loads((RAW.parent / "dataset_meta.json").read_text(encoding="utf-8"))
    tables = load()
    snap, fact_month = snapshot(tables, meta)
    star_schema(tables, meta, fact_month)
    REPORT.mkdir(parents=True, exist_ok=True)
    (REPORT / "metrics_snapshot.json").write_text(json.dumps(snap, indent=2), encoding="utf-8")
    trend_report(snap)
    k = snap["kpis"]
    print(f"As of {snap['as_of']}: {k['live']} live systems, coverage {k['implemented']}/{k['required']}, "
          f"effectiveness {k['effective']}/{k['required']}, evidence current {k['evidence_current']}/{k['required']}, "
          f"open critical {k['open_critical']}")
    print(f"Wrote {len(list(OUT.glob('*.csv')))} Power BI tables to {OUT.relative_to(ROOT)}")
