"""Data quality checks for the raw governance tables. Standard library only.

Run:  python analytics/quality_checks.py      (exit code 1 if any check fails)

Checks cover the things that silently break governance metrics: duplicate keys, orphaned
foreign keys, impossible date orders, values outside their domain, and records dated after
the reporting date.
"""
import csv
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "analytics" / "data" / "raw"
META = json.loads((RAW.parent / "dataset_meta.json").read_text(encoding="utf-8"))
AS_OF = META["as_of"]

T = {p.stem: list(csv.DictReader(p.open(encoding="utf-8"))) for p in RAW.glob("*.csv")}
results = []


def check(name, bad):
    bad = list(bad)
    results.append((name, len(bad), bad[:3]))


def keys(table, column):
    return {r[column] for r in T[table]}


PRIMARY = {"business_units": "bu_id", "owners": "owner_id", "models": "model_id", "controls": "control_id",
           "ai_systems": "system_id", "control_tests": "test_id", "evidence": "evidence_id", "findings": "finding_id",
           "remediation_actions": "action_id", "exceptions": "exception_id", "incidents": "incident_id", "incident_refunds": "refund_id",
           "model_changes": "change_id", "lifecycle_events": "event_id"}
for table, pk in PRIMARY.items():
    seen, dupes = set(), []
    for r in T[table]:
        if r[pk] in seen or not r[pk]:
            dupes.append(r[pk])
        seen.add(r[pk])
    check(f"primary key unique and present: {table}.{pk}", dupes)
pairs = [(r["system_id"], r["control_id"]) for r in T["system_controls"]]
check("composite key unique: system_controls(system_id, control_id)", {p for p in pairs if pairs.count(p) > 1})

FOREIGN = [("owners", "bu_id", "business_units", "bu_id"), ("ai_systems", "bu_id", "business_units", "bu_id"),
           ("ai_systems", "owner_id", "owners", "owner_id"), ("ai_systems", "model_id", "models", "model_id"),
           ("findings", "owner_id", "owners", "owner_id"), ("remediation_actions", "finding_id", "findings", "finding_id"),
           ("model_changes", "model_id", "models", "model_id"), ("incident_refunds", "incident_id", "incidents", "incident_id")]
for table in ["system_controls", "control_tests", "evidence", "findings", "exceptions", "incidents", "incident_refunds", "model_changes", "lifecycle_events"]:
    FOREIGN.append((table, "system_id", "ai_systems", "system_id"))
for table in ["system_controls", "control_tests", "evidence", "findings", "exceptions"]:
    FOREIGN.append((table, "control_id", "controls", "control_id"))
for child, column, parent, parent_column in FOREIGN:
    valid = keys(parent, parent_column)
    check(f"foreign key resolves: {child}.{column} -> {parent}", [r[column] for r in T[child] if r[column] not in valid])

required = {(r["system_id"], r["control_id"]) for r in T["system_controls"]}
for table in ["control_tests", "evidence", "findings", "exceptions"]:
    check(f"{table} reference a control that is required for that system",
          [(r["system_id"], r["control_id"]) for r in T[table] if (r["system_id"], r["control_id"]) not in required])

DOMAINS = [("ai_systems", "inherent_tier", {"Low", "Moderate", "High", "Critical"}),
           ("ai_systems", "lifecycle_status", {"Proposed", "In assessment", "Approved", "Production", "Suspended", "Retired"}),
           ("control_tests", "result", {"Pass", "Fail"}), ("findings", "severity", {"Critical", "High", "Medium", "Low"}),
           ("incidents", "severity", {"Sev1", "Sev2", "Sev3", "Sev4"})]
for table, column, allowed in DOMAINS:
    check(f"domain: {table}.{column}", [r[column] for r in T[table] if r[column] not in allowed])
for column in [c for c in T["ai_systems"][0] if c.startswith("f_")]:
    check(f"range 0-3: ai_systems.{column}", [r[column] for r in T["ai_systems"] if r[column] not in "0123" or r[column] == ""])

ORDER = [("ai_systems", "registered_date", "production_date"), ("ai_systems", "production_date", "retired_date"),
         ("findings", "opened_date", "due_date"), ("findings", "opened_date", "closed_date"),
         ("evidence", "collected_date", "valid_until"), ("exceptions", "granted_date", "expiry_date"),
         ("incidents", "detected_date", "resolved_date"), ("model_changes", "change_date", "reassessment_completed_date")]
for table, first, second in ORDER:
    check(f"date order: {table}.{first} <= {second}", [(r[first], r[second]) for r in T[table] if r[first] and r[second] and r[first] > r[second]])

EVENT_DATES = [("control_tests", "test_date"), ("findings", "opened_date"), ("findings", "closed_date"), ("evidence", "collected_date"),
               ("incidents", "detected_date"), ("model_changes", "change_date"), ("lifecycle_events", "event_date"), ("exceptions", "granted_date")]
for table, column in EVENT_DATES:
    check(f"not dated after reporting date: {table}.{column}", [r[column] for r in T[table] if r[column] > AS_OF])

systems = {r["system_id"]: r for r in T["ai_systems"]}
check("no control test before the system went live",
      [r["test_id"] for r in T["control_tests"] if not systems[r["system_id"]]["production_date"] or r["test_date"] < systems[r["system_id"]]["production_date"]])
check("production systems have an owner and review dates",
      [s["system_id"] for s in T["ai_systems"] if s["lifecycle_status"] == "Production" and not (s["owner_id"] and s["next_review_date"])])
# Incident INC-0031: the refund records are the source, and the figures quoted in the incident record must follow from them.
POLICY = json.loads((ROOT / "analytics" / "policy" / "policy_rules.json").read_text(encoding="utf-8"))
LIMITS = POLICY["agent_policy"]["limits"]
RF = [r for r in T["incident_refunds"] if r["incident_id"] == "INC-0031"]
INC = next(r for r in T["incidents"] if r["incident_id"] == "INC-0031")
day_totals = {}
for r in RF:
    day_totals[(r["customer_ref"], r["refund_date"])] = day_totals.get((r["customer_ref"], r["refund_date"]), 0) + int(r["amount_usd"])
rf_total = sum(int(r["amount_usd"]) for r in RF)
check("incident refunds: each amount is positive and at or under the autonomous limit",
      [r["refund_id"] for r in RF if not 0 < int(r["amount_usd"]) <= LIMITS["auto_refund_max"]])
check("incident refunds: total cannot exceed count x autonomous limit", [rf_total] if rf_total > len(RF) * LIMITS["auto_refund_max"] else [])
check("incident refunds: every customer-day total is above the cumulative daily level",
      [k for k, v in day_totals.items() if v <= LIMITS["daily_cumulative_per_customer"]])
running, bad_prior = {}, []
for r in sorted(RF, key=lambda r: (r["customer_ref"], r["refund_date"], int(r["sequence_in_day"]))):
    key = (r["customer_ref"], r["refund_date"])
    if int(r["prior_refunds_today_usd"]) != running.get(key, 0):
        bad_prior.append(r["refund_id"])
    running[key] = running.get(key, 0) + int(r["amount_usd"])
check("incident refunds: prior_refunds_today_usd equals the running total", bad_prior)
check("incident refunds: issued on or before the incident was detected", [r["refund_id"] for r in RF if r["refund_date"] > INC["detected_date"]])
above = sum(v - LIMITS["daily_cumulative_per_customer"] for v in day_totals.values())
quoted = [f"{len(RF)} refunds", f"{len({r['customer_ref'] for r in RF})} customers", f"total ${rf_total:,}.", f"${above:,} above"]
check("incident refunds: figures in the INC-0031 description match the records", [q for q in quoted if q not in INC["description"]])
check("row counts match dataset_meta.json", [n for n, c in META["row_counts"].items() if len(T[n]) != c])

failed = [r for r in results if r[1]]
for name, count, sample in results:
    print(f"{'FAIL' if count else 'pass'}  {name}" + (f"  ({count} rows, e.g. {sample})" if count else ""))
print(f"\n{len(results) - len(failed)} of {len(results)} checks passed")
(ROOT / "analytics" / "output").mkdir(exist_ok=True)
(ROOT / "analytics" / "output" / "quality_report.json").write_text(json.dumps(
    {"as_of": AS_OF, "checks": len(results), "failed": len(failed), "results": [{"check": n, "failing_rows": c} for n, c, _ in results]}, indent=2), encoding="utf-8")
sys.exit(1 if failed else 0)
