"""Reproducible synthetic AI governance dataset for the fictional Larkmoor Financial Group.

Run:  python analytics/generate_data.py
Uses the Python standard library only. A fixed seed makes every run identical.

Outputs
  analytics/data/raw/*.csv            one file per table (see docs/DATA_DICTIONARY.md)
  assets/data/governance-data.js      the same tables, bundled for the website
  assets/data/policy-data.js          policy_rules.json, bundled for the website

Nothing here describes a real organization, person, vendor, incident or result.
"""
import csv
import json
import random
import sys
from datetime import date, timedelta
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))
from policy_engine import assess, load_policy  # noqa: E402

SEED = 42001
AS_OF = date(2026, 10, 31)
WINDOW_START = date(2025, 11, 1)
HISTORY_START = date(2025, 5, 1)   # tests and evidence before the window feed look-back metrics
ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "analytics" / "data" / "raw"
HERO = "AIS-014"

rng = random.Random(SEED)
policy = load_policy()
CONTROLS = {c["id"]: c for c in policy["controls"]}
FACTOR_IDS = [f["id"] for f in policy["factors"]]
TIERS = policy["tiers"]


def d(days):
    return timedelta(days=days)


def iso(value):
    return value.isoformat() if value else ""


def between(start, end):
    return start + d(rng.randint(0, max(0, (end - start).days)))


def clamp(value, low, high):
    return max(low, min(high, value))


# ---------------------------------------------------------------- reference data
BUSINESS_UNITS = [
    # id, name, accountable executive, executive title, maturity (drives synthetic control health)
    ("BU-RB", "Retail Banking", "Marisol Okafor", "Head of Retail Banking", 0.82),
    ("BU-CO", "Customer Operations", "Dev Ramaswamy", "Chief Customer Operations Officer", 0.74),
    ("BU-CP", "Cards & Payments", "Ingrid Solheim", "Head of Cards & Payments", 0.86),
    ("BU-WM", "Wealth Management", "Tobias Lindqvist", "Head of Wealth Management", 0.78),
    ("BU-CL", "Commercial Lending", "Renee Abernathy", "Head of Commercial Lending", 0.70),
    ("BU-RC", "Risk & Compliance", "Kwame Asante", "Chief Risk Officer", 0.90),
    ("BU-TS", "Technology & Shared Services", "Yuki Tanabe", "Chief Information Officer", 0.66),
    ("BU-CF", "Corporate Functions", "Laila Haddad", "Chief Administrative Officer", 0.60),
]

OWNER_NAMES = [
    "Aarav Mehta", "Bianca Rossi", "Carlos Mendez", "Dana Whitfield", "Emeka Obi", "Farah Siddiqui",
    "Gideon Clarke", "Hana Kobayashi", "Isaac Feldman", "Jocelyn Tran", "Kofi Boateng", "Lena Novak",
    "Mateo Alvarez", "Nia Robinson", "Omar Farouk", "Priya Nair", "Quentin Hale", "Rosa Delgado",
    "Samir Patel", "Tessa Brennan", "Uma Krishnan", "Victor Lang", "Wren Castillo", "Zofia Kowalski",
]
OWNER_TITLES = ["Product owner", "Operations lead", "Analytics lead"]

MODELS = [
    ("MDL-01", "Northlake AI", "NL-4 Large", "Hosted API", 1),
    ("MDL-02", "Northlake AI", "NL-4 Mini", "Hosted API", 1),
    ("MDL-03", "Vireo Labs", "Vireo 3", "Hosted API", 2),
    ("MDL-04", "Cobalt Systems", "Atlas XL", "Private cloud tenancy", 1),
    ("MDL-05", "In-house", "Gradient-boosted models", "Internal platform", 0),
    ("MDL-06", "In-house", "Fine-tuned open-weight LLM", "Internal platform", 0),
    ("MDL-07", "Embedded vendor AI", "SaaS feature (varies)", "Vendor SaaS", 3),
    ("MDL-08", "In-house", "Rules plus classical NLP", "Internal platform", 0),
]

# archetype -> base factor levels in FACTOR_IDS order
ARCHETYPES = {
    "assist":    [1, 0, 1, 0, 0, 0, 2, 1, 0],
    "summarize": [1, 0, 2, 0, 0, 0, 2, 1, 1],
    "triage":    [2, 1, 2, 1, 1, 1, 1, 1, 1],
    "content":   [2, 1, 2, 1, 1, 2, 1, 1, 1],
    "decision":  [3, 2, 3, 1, 0, 2, 1, 0, 3],
    "agent":     [3, 2, 3, 3, 1, 3, 1, 1, 2],
    "agent_int": [2, 1, 2, 2, 1, 0, 1, 1, 1],
    "model":     [2, 2, 2, 1, 2, 1, 1, 0, 2],
    "vendor":    [1, 0, 1, 1, 1, 0, 2, 3, 0],
    "fraud":     [3, 3, 3, 2, 1, 3, 0, 0, 2],
    "credit":    [3, 3, 3, 1, 1, 3, 1, 0, 3],
}

SYSTEMS = [
    ("BU-RB", "Branch Knowledge Assistant", "Answers staff questions from approved product and procedure content.", "assist"),
    ("BU-RB", "Deposit Product Explainer", "Drafts plain-language product explanations for customers, reviewed by bankers.", "content"),
    ("BU-RB", "Mortgage Document Summarizer", "Summarizes borrower documents for processors.", "summarize"),
    ("BU-RB", "Account Opening Identity Assist", "Flags identity mismatches during account opening for a banker decision.", "decision"),
    ("BU-RB", "Customer Email Drafting Assistant", "Drafts replies to customer email for banker review and sending.", "content"),
    ("BU-RB", "Overdraft Outreach Prioritizer", "Ranks customers for proactive overdraft outreach.", "model"),
    ("BU-RB", "Branch Staffing Forecaster", "Forecasts branch traffic to support staffing plans.", "assist"),
    ("BU-RB", "Complaint Theme Classifier", "Classifies complaint text into themes for reporting.", "triage"),
    ("BU-RB", "Savings Goal Coach", "Suggests savings nudges inside the mobile app.", "content"),
    ("BU-RB", "Teller Procedure Search", "Searches teller procedures in natural language.", "assist"),
    ("BU-CO", "Contact Center Call Summarizer", "Writes after-call summaries for service representatives.", "summarize"),
    ("BU-CO", "Service Request Triage Classifier", "Routes incoming service requests to the right queue.", "triage"),
    ("BU-CO", "Agent Assist Knowledge Copilot", "Suggests knowledge articles to representatives during calls.", "assist"),
    ("BU-CO", "Refund Resolution Agent", "Resolves fee and service refund requests in chat: reads the authenticated customer's account and issues refunds within policy limits.", "agent"),
    ("BU-CO", "Address Change Verification Assistant", "Checks address change requests against verification rules before a representative approves.", "agent_int"),
    ("BU-CO", "Customer Chat Virtual Assistant", "Answers general servicing questions in customer chat.", "content"),
    ("BU-CO", "Complaint Response Drafter", "Drafts complaint responses for specialist review.", "content"),
    ("BU-CO", "Callback Scheduling Agent", "Books customer callbacks after a representative confirms.", "agent_int"),
    ("BU-CO", "Quality Monitoring Scorer", "Scores recorded calls against the quality rubric.", "triage"),
    ("BU-CO", "Voice Authentication Model", "Scores voice match as one factor in caller authentication.", "decision"),
    ("BU-CO", "Fee Waiver Recommendation Assistant", "Recommends fee waivers for a representative to accept or decline.", "model"),
    ("BU-CP", "Card Fraud Auto-Decline Model", "Declines card transactions in real time above a fraud score threshold.", "fraud"),
    ("BU-CP", "Dispute Intake Assistant", "Collects dispute details from cardholders and classifies the dispute type.", "triage"),
    ("BU-CP", "Chargeback Evidence Compiler", "Assembles chargeback evidence packets for analyst approval.", "agent_int"),
    ("BU-CP", "Merchant Category Classifier", "Assigns merchant categories for reporting.", "assist"),
    ("BU-CP", "Payment Exception Router", "Routes failed payments to exception queues.", "triage"),
    ("BU-CP", "Card Limit Increase Recommender", "Recommends credit line changes for underwriter decision.", "credit"),
    ("BU-CP", "Transaction Dispute Resolution Agent", "Issues provisional credits for low-value disputes within limits.", "agent"),
    ("BU-CP", "Rewards Offer Personalizer", "Selects rewards offers shown to cardholders.", "model"),
    ("BU-CP", "Payments Reconciliation Matcher", "Proposes matches for unreconciled payments for analyst approval.", "agent_int"),
    ("BU-CP", "Card Servicing Chat Assistant", "Answers card servicing questions in chat.", "content"),
    ("BU-WM", "Advisor Meeting Summarizer", "Summarizes client meetings into advisor notes.", "summarize"),
    ("BU-WM", "Portfolio Commentary Drafter", "Drafts portfolio commentary for advisor editing.", "content"),
    ("BU-WM", "Suitability Review Assistant", "Flags potential suitability concerns for compliance review.", "decision"),
    ("BU-WM", "Client Document Extractor", "Extracts fields from client-provided documents.", "summarize"),
    ("BU-WM", "Research Digest Copilot", "Summarizes internal research for advisors.", "assist"),
    ("BU-WM", "Advisor Next-Best-Action Model", "Ranks suggested client outreach for advisors.", "model"),
    ("BU-WM", "Trade Surveillance Alert Triage", "Prioritizes trade surveillance alerts for analysts.", "triage"),
    ("BU-WM", "Client Onboarding Form Assistant", "Helps clients complete onboarding forms.", "triage"),
    ("BU-WM", "Market Brief Generator", "Drafts a daily internal market brief.", "assist"),
    ("BU-CL", "Credit Memo Drafting Assistant", "Drafts sections of credit memos for underwriters.", "summarize"),
    ("BU-CL", "Financial Spreading Extractor", "Extracts financial statement values for spreading.", "summarize"),
    ("BU-CL", "Small Business Credit Scoring Model", "Scores small business applications as an input to credit decisions.", "credit"),
    ("BU-CL", "Covenant Monitoring Agent", "Checks covenant compliance and opens cases for relationship managers to approve.", "agent_int"),
    ("BU-CL", "Loan Document Comparison Tool", "Compares loan document versions and highlights changes.", "assist"),
    ("BU-CL", "Collateral Valuation Estimator", "Estimates collateral values for review.", "model"),
    ("BU-CL", "Borrower Early-Warning Model", "Flags borrowers showing signs of stress.", "model"),
    ("BU-CL", "Pipeline Forecasting Assistant", "Forecasts loan pipeline conversion.", "assist"),
    ("BU-CL", "Commercial Onboarding KYC Assistant", "Pre-screens commercial onboarding files for analyst decision.", "decision"),
    ("BU-RC", "AML Alert Triage Model", "Prioritizes anti-money-laundering alerts for investigators.", "credit"),
    ("BU-RC", "Sanctions Screening Match Resolver", "Proposes dispositions for sanctions screening matches for analyst decision.", "decision"),
    ("BU-RC", "Policy Q&A Copilot", "Answers staff questions about internal policy.", "assist"),
    ("BU-RC", "Regulatory Change Summarizer", "Summarizes regulatory publications for compliance analysts.", "summarize"),
    ("BU-RC", "Model Documentation Assistant", "Drafts model documentation sections for validators.", "assist"),
    ("BU-RC", "Audit Workpaper Drafter", "Drafts audit workpaper narratives for auditors.", "summarize"),
    ("BU-RC", "Fraud Ring Detection Model", "Identifies linked accounts for fraud investigators.", "model"),
    ("BU-RC", "Control Testing Sampler", "Selects samples for control testing.", "assist"),
    ("BU-RC", "Suspicious Activity Narrative Drafter", "Drafts narratives for investigator editing.", "summarize"),
    ("BU-TS", "Developer Code Assistant", "Suggests code inside developer tools.", "vendor"),
    ("BU-TS", "IT Service Desk Agent", "Resolves routine IT tickets after employee confirmation.", "agent_int"),
    ("BU-TS", "Incident Postmortem Summarizer", "Summarizes incident timelines for postmortems.", "assist"),
    ("BU-TS", "Access Request Auto-Approver", "Approves low-risk access requests against entitlement rules.", "agent_int"),
    ("BU-TS", "Log Anomaly Detector", "Flags unusual log patterns for engineers.", "assist"),
    ("BU-TS", "Test Case Generator", "Generates test cases from requirements.", "assist"),
    ("BU-TS", "Infrastructure Cost Advisor", "Recommends infrastructure cost savings.", "assist"),
    ("BU-TS", "Security Alert Enrichment Agent", "Enriches security alerts and proposes containment for analyst approval.", "agent_int"),
    ("BU-TS", "Change Risk Classifier", "Classifies change requests by risk.", "triage"),
    ("BU-CF", "Candidate Screening Assistant", "Ranks applications for recruiter review.", "decision"),
    ("BU-CF", "HR Policy Chatbot", "Answers employee questions about HR policy.", "triage"),
    ("BU-CF", "Contract Review Assistant", "Summarizes contract issues for legal review.", "summarize"),
    ("BU-CF", "Invoice Processing Agent", "Codes and queues invoices for payment approval.", "agent_int"),
    ("BU-CF", "Expense Audit Classifier", "Flags expense reports for audit.", "triage"),
    ("BU-CF", "Procurement Comparison Copilot", "Drafts supplier comparisons for buyers.", "vendor"),
    ("BU-CF", "Marketing Copy Generator", "Drafts marketing copy for brand and compliance review.", "vendor"),
    ("BU-CF", "Board Pack Summarizer", "Summarizes board materials for the corporate secretary.", "summarize"),
]
assert len(SYSTEMS) == 75

ISSUES = [
    "evidence did not cover the full population", "configuration drifted from the approved baseline",
    "review was performed after the due date", "approver was not on the authorized list",
    "test sample showed exceptions above tolerance", "procedure not updated after a system change",
    "alert was raised but not routed to a named responder", "documentation did not match deployed behavior",
]
ACTIONS = [
    "Correct configuration and capture new evidence", "Update procedure and brief reviewers",
    "Re-perform the control test on a full sample", "Assign named responder and test alert routing",
    "Reconcile documentation with deployed behavior", "Complete overdue review and record outcome",
]
EXCEPTION_REASONS = [
    ("Control dependent on platform release scheduled next quarter", "Manual weekly review by the system owner"),
    ("Vendor cannot yet provide required attestation", "Contractual restriction on data categories sent"),
    ("Pilot with restricted user group", "Usage limited to named pilot users and daily log review"),
    ("Tooling migration in progress", "Legacy control operated manually during migration"),
]
INCIDENT_TYPES = [
    # category, weight, typical descriptions
    ("Policy violation blocked", 30, "Agent or user request outside policy was blocked by a control and logged."),
    ("Prompt injection attempt", 16, "Untrusted content attempted to change system instructions; attempt was detected."),
    ("Output quality degradation", 22, "Monitoring showed accuracy or groundedness below threshold."),
    ("Unauthorized action executed", 6, "An action completed that policy should have held or blocked."),
    ("Sensitive data exposure", 8, "Output or log contained data outside the permitted scope."),
    ("Third-party service disruption", 18, "Provider outage or change degraded the service."),
]
SEVERITIES = ["Sev1", "Sev2", "Sev3", "Sev4"]


# ---------------------------------------------------------------- incident INC-0031 source records
HERO_INCIDENT = "INC-0031"


def hero_refund_records():
    """Transaction-level source for incident INC-0031 (split refunds by the Refund Resolution Agent).

    Every figure quoted about the incident (refund count, customers, total, amount above the daily
    level) is derived from these rows; nothing is typed in separately. Assumptions, all synthetic:
      * every refund happened on one day, 2026-09-08, and was found by the next morning's reconciliation;
      * each refund is at or under the autonomous limit, so policy v1.0 allowed each one (rule AP-08);
      * every customer's day total is above the cumulative daily level that policy v1.1 later set,
        which needs at least three refunds per customer at the current limits;
      * the first customer is the worked example used in the scenario and the lab ($140 three times).
    Uses its own random stream so the rest of the dataset is unchanged.
    """
    r = random.Random(SEED + 31)
    limits = policy["agent_policy"]["limits"]
    auto, daily = limits["auto_refund_max"], limits["daily_cumulative_per_customer"]
    day = date(2026, 9, 8)
    rows = []
    for c in range(1, 15):
        n = 4 if c in (6, 11) else 3
        if c == 1:
            amounts = [140, 140, 140]
        else:
            while True:
                amounts = [r.randrange(70 if n == 4 else 90, auto, 5) for _ in range(n)]
                if sum(amounts) > daily and sum(amounts[:2]) <= daily:
                    break
        prior = 0
        for seq, amount in enumerate(amounts, 1):
            rows.append(dict(refund_id=f"RF-{len(rows) + 1:04d}", incident_id=HERO_INCIDENT, system_id=HERO,
                             customer_ref=f"CUST-{c:02d}", refund_date=iso(day), sequence_in_day=seq,
                             amount_usd=amount, prior_refunds_today_usd=prior, policy_version="1.0",
                             rule_applied="AP-08", supervisor_reviewed=0))
            prior += amount
    return rows


def refund_summary(rows):
    limits = policy["agent_policy"]["limits"]
    daily = limits["daily_cumulative_per_customer"]
    by_customer = {}
    for row in rows:
        by_customer[row["customer_ref"]] = by_customer.get(row["customer_ref"], 0) + row["amount_usd"]
    return dict(refunds=len(rows), customers=len(by_customer), total=sum(by_customer.values()),
                above_daily=sum(max(0, v - daily) for v in by_customer.values()),
                auto=limits["auto_refund_max"], daily=daily, day=rows[0]["refund_date"])


HERO_REFUNDS = hero_refund_records()
HERO_REFUND_SUMMARY = refund_summary(HERO_REFUNDS)


# ---------------------------------------------------------------- generation
def build():
    t = {name: [] for name in [
        "business_units", "owners", "models", "controls", "ai_systems", "system_controls", "control_tests",
        "evidence", "findings", "remediation_actions", "exceptions", "incidents", "incident_refunds", "model_changes", "lifecycle_events"]}

    maturity = {}
    for bu_id, name, executive, title, m in BUSINESS_UNITS:
        maturity[bu_id] = m
        t["business_units"].append(dict(bu_id=bu_id, bu_name=name, accountable_executive=executive, executive_title=title))

    owners_by_bu = {}
    for i, name in enumerate(OWNER_NAMES):
        bu_id = BUSINESS_UNITS[i // 3][0]
        owner_id = f"OWN-{i + 1:02d}"
        owners_by_bu.setdefault(bu_id, []).append(owner_id)
        t["owners"].append(dict(owner_id=owner_id, owner_name=name, owner_title=OWNER_TITLES[i % 3], bu_id=bu_id))

    for model_id, provider, model_name, hosting, third in MODELS:
        t["models"].append(dict(model_id=model_id, provider=provider, model_name=model_name, hosting=hosting))
    models_by_third = {}
    for m in MODELS:
        models_by_third.setdefault(m[4], []).append(m[0])

    for c in policy["controls"]:
        t["controls"].append(dict(
            control_id=c["id"], control_name=c["name"], domain=c["domain"], objective=c["objective"],
            is_critical=int(c["critical"]), evidence_required=c["evidence"], control_owner_role=c["owner_role"],
            test_frequency_days=c["test_days"], evidence_validity_days=c["evidence_days"],
            nist_ai_rmf=" | ".join(c["nist"]), iso_42001=" | ".join(c["iso"]), owasp_genai=" | ".join(c["owasp"])))

    # lifecycle allocation: exact counts, hero forced to Production
    statuses = (["Production"] * 46 + ["In assessment"] * 8 + ["Proposed"] * 5 + ["Approved"] * 5
                + ["Suspended"] * 3 + ["Retired"] * 7)
    rng.shuffle(statuses)
    statuses.insert(13, "Production")
    assert len(statuses) == 75

    health = {}
    counters = dict(test=0, ev=0, fnd=0, ra=0, exc=0, mc=0, le=0)

    def next_id(kind, prefix, width):
        counters[kind] += 1
        return f"{prefix}-{counters[kind]:0{width}d}"

    def event(system_id, when, kind, actor, note=""):
        if when and when <= AS_OF:
            t["lifecycle_events"].append(dict(event_id="", system_id=system_id, event_date=iso(when),
                                               event_type=kind, actor_role=actor, note=note))

    for idx, (bu_id, name, purpose, archetype) in enumerate(SYSTEMS):
        system_id = f"AIS-{idx + 1:03d}"
        hero = system_id == HERO
        status = statuses[idx]
        levels = list(ARCHETYPES[archetype])
        if not hero:
            for k in range(len(levels)):
                if rng.random() < 0.22:
                    levels[k] = clamp(levels[k] + rng.choice([-1, 1]), 0, 3)
        factors = dict(zip(FACTOR_IDS, levels))
        if factors["autonomy"] >= 3:
            factors["human_oversight"] = min(factors["human_oversight"], 2)      # avoid prohibited config P1
        if factors["data_sensitivity"] >= 3:
            factors["third_party"] = min(factors["third_party"], 2)              # avoid prohibited config P2
        model_id = "MDL-01" if hero else rng.choice(models_by_third[factors["third_party"]] if factors["third_party"] in models_by_third
                                                    else models_by_third[1])
        result = assess(factors, policy)
        tier = result["tier"]
        h = 0.93 if hero else clamp(maturity[bu_id] + rng.gauss(0, 0.09), 0.35, 0.98)
        health[system_id] = h
        owner_id = owners_by_bu[bu_id][0] if hero else rng.choice(owners_by_bu[bu_id])

        # dates
        production = retired = suspended = approved = None
        if hero:
            registered, approved, production = date(2025, 11, 10), date(2026, 2, 12), date(2026, 3, 2)
        elif status in ("Production", "Suspended", "Retired"):
            registered = between(date(2024, 3, 1), date(2026, 4, 15))
            production = registered + d(rng.randint(60, 150))
            approved = production - d(rng.randint(7, 21))
            if status == "Retired":
                registered = between(date(2024, 3, 1), date(2025, 3, 1))
                production = registered + d(rng.randint(60, 150))
                approved = production - d(rng.randint(7, 21))
                retired = between(date(2026, 1, 10), date(2026, 9, 20))
            if status == "Suspended":
                suspended = between(date(2026, 8, 5), date(2026, 10, 20))
        elif status == "Approved":
            registered = between(date(2026, 4, 1), date(2026, 8, 1))
            approved = between(date(2026, 9, 15), date(2026, 10, 25))
        elif status == "In assessment":
            registered = between(date(2026, 6, 15), date(2026, 9, 30))
        else:
            registered = between(date(2026, 8, 20), date(2026, 10, 25))

        interval = policy["review_interval_days"][tier]
        last_review = next_review = None
        if hero:
            last_review, next_review = date(2026, 10, 20), date(2026, 12, 19)
        elif status in ("Production", "Suspended"):
            last_review = AS_OF - d(int(rng.random() * interval * (1.9 - 0.8 * h)))
            last_review = max(last_review, production)
            next_review = last_review + d(interval)
        elif status == "Approved":
            last_review, next_review = approved, approved + d(interval)

        t["ai_systems"].append(dict(
            system_id=system_id, system_name=name, bu_id=bu_id, business_purpose=purpose, owner_id=owner_id,
            model_id=model_id, lifecycle_status=status, registered_date=iso(registered), approved_date=iso(approved),
            production_date=iso(production), suspended_date=iso(suspended), retired_date=iso(retired),
            **{f"f_{k}": v for k, v in factors.items()},
            autonomy_level=f"A{factors['autonomy']}",
            data_sensitivity=["Public", "Internal", "Confidential", "Restricted"][factors["data_sensitivity"]],
            customer_facing=int(factors["external_impact"] >= 2),
            inherent_score=round(result["score"], 1), inherent_tier=tier,
            last_review_date=iso(last_review), next_review_date=iso(next_review)))

        if not hero:
            event(system_id, registered, "Registered", "System owner")
            if status != "Proposed":
                event(system_id, registered + d(rng.randint(8, 30)), "Risk assessed", "Business unit risk lead", f"Inherent tier {tier}")
            event(system_id, approved, "Release authorized", "AI Governance Committee" if tier == "Critical" else "AI Risk (second line)" if tier == "High" else "Business unit risk lead")
            event(system_id, production, "Deployed", "System owner")
            event(system_id, suspended, "Suspended", "Operations control owner", "Suspended pending remediation")
            event(system_id, retired, "Retired", "System owner")

        # required controls and implementation
        anchor = production or approved
        for control_id in result["required_controls"]:
            control = CONTROLS[control_id]
            implemented = None
            if hero:
                implemented = date(2026, 9, 26) if control_id == "FIN-02" else date(2026, 2, 6)
            elif anchor:
                p = 0.78 + 0.22 * h + (0.06 if control["critical"] else 0)
                if rng.random() < p:
                    implemented = anchor - d(rng.randint(5, 40))
                    if rng.random() < 0.12:
                        implemented = anchor + d(rng.randint(20, 200))
            elif status == "In assessment" and rng.random() < 0.35:
                implemented = between(registered, AS_OF)
            if implemented and implemented > AS_OF:
                implemented = None
            t["system_controls"].append(dict(system_id=system_id, control_id=control_id, implemented_date=iso(implemented)))
            if not implemented:
                continue

            # evidence refresh cycle
            stop = retired or AS_OF
            when = implemented
            while when <= stop:
                valid_until = when + d(control["evidence_days"])
                if valid_until >= HISTORY_START:
                    t["evidence"].append(dict(
                        evidence_id=next_id("ev", "EV", 5), system_id=system_id, control_id=control_id,
                        evidence_type=control["evidence"], collected_date=iso(when), valid_until=iso(valid_until),
                        collected_by_role=control["owner_role"],
                        source_system=rng.choice(["GRC repository", "Ticketing system", "CI pipeline", "Log platform"])))
                gap = rng.randint(-20, 10)
                if not hero and rng.random() < 0.20 * (1.5 - h):
                    gap = rng.randint(30, 170)     # refresh lapsed: evidence goes stale for a while
                when = valid_until + d(gap)

            # control tests (only once a system is live)
            if not production:
                continue
            when = max(implemented, production, HISTORY_START) + d(rng.randint(0, control["test_days"] if max(implemented, production) < HISTORY_START else 25))
            while when <= stop:
                hero_override = hero and control_id in ("HUM-01", "SEC-02", "FIN-02") and when >= date(2026, 9, 1)
                skipped = (not hero) and rng.random() < 0.10 * (1.5 - h)
                if not hero_override and not skipped:
                    trend = 0.05 * (when - WINDOW_START).days / 365
                    p_pass = 0.70 + 0.27 * h + trend - (0.05 if control["domain"] in ("Security", "Human oversight") else 0)
                    if suspended and when >= suspended - d(60):
                        p_pass -= 0.25
                    passed = rng.random() < clamp(p_pass, 0.4, 0.985)
                    line = "Second line" if control["critical"] and rng.random() < 0.5 else "Internal audit" if rng.random() < 0.04 else "First line"
                    add_test(t, next_id, system_id, control_id, when, passed, line, h, owner_id)
                when = when + d(control["test_days"] + rng.randint(-10, 12))

        # exceptions for unimplemented required controls on live systems
        if status in ("Production", "Suspended") and not hero:
            for row in [r for r in t["system_controls"] if r["system_id"] == system_id and not r["implemented_date"]]:
                if rng.random() < 0.6:
                    reason, compensating = rng.choice(EXCEPTION_REASONS)
                    granted = between(max(production, date(2025, 9, 1)), date(2026, 9, 30))
                    expiry = granted + d(rng.choice([90, 180]))
                    closed = None
                    if expiry <= AS_OF and rng.random() < 0.55:
                        closed = expiry - d(rng.randint(0, 10))
                    t["exceptions"].append(dict(
                        exception_id=next_id("exc", "EXC", 4), system_id=system_id, control_id=row["control_id"],
                        rationale=reason, compensating_control=compensating,
                        approved_by_role="AI Governance Committee" if tier == "Critical" else "AI Risk (second line)",
                        granted_date=iso(granted), expiry_date=iso(expiry), closed_date=iso(closed)))

    # additional findings from audit and second-line reviews
    live = [s for s in t["ai_systems"] if s["production_date"] and s["system_id"] != HERO]
    for n in range(26):
        s = rng.choice(live)
        required = [r["control_id"] for r in t["system_controls"] if r["system_id"] == s["system_id"]]
        opened = between(max(date.fromisoformat(s["production_date"]), WINDOW_START), min(AS_OF, date.fromisoformat(s["retired_date"]) if s["retired_date"] else AS_OF))
        source = rng.choice(["Internal audit", "Second-line review"])
        if n < 5 and not s["retired_date"]:
            # Seeded on purpose: a handful of recent, still-open Critical findings so the
            # leadership-attention workflow has realistic content to act on.
            critical = [c for c in required if CONTROLS[c]["critical"]] or required
            add_finding(t, next_id, s["system_id"], rng.choice(critical), between(date(2026, 9, 12), date(2026, 10, 24)), source,
                        health[s["system_id"]], s["owner_id"], severity="Critical", closed=None)
        else:
            add_finding(t, next_id, s["system_id"], rng.choice(required), opened, source, health[s["system_id"]], s["owner_id"])

    add_hero_story(t, next_id, event)
    add_incidents(t)
    add_model_changes(t, next_id, health)

    t["lifecycle_events"].sort(key=lambda r: (r["event_date"], r["system_id"]))
    for i, row in enumerate(t["lifecycle_events"], 1):
        row["event_id"] = f"LE-{i:04d}"
    for name in ("control_tests", "findings"):
        t[name].sort(key=lambda r: r[list(r)[0]])
    return t


def add_test(t, next_id, system_id, control_id, when, passed, line, h, owner_id, spawn=True):
    test_id = next_id("test", "CT", 5)
    t["control_tests"].append(dict(
        test_id=test_id, system_id=system_id, control_id=control_id, test_date=iso(when),
        result="Pass" if passed else "Fail", tested_by_line=line,
        method=rng.choice(["Inspection", "Reperformance", "Automated check"])))
    if spawn and not passed and when >= date(2025, 9, 1) and rng.random() < 0.55:
        add_finding(t, next_id, system_id, control_id, when + d(rng.randint(0, 5)), "Control test", h, owner_id, test_id)


def add_finding(t, next_id, system_id, control_id, opened, source, h, owner_id, test_id="", severity=None, title=None, due=None, closed="auto"):
    control = CONTROLS[control_id]
    if opened > AS_OF:
        return
    if severity is None:
        weights = [22, 43, 30, 5] if control["critical"] else [3, 20, 50, 27]
        severity = rng.choices(["Critical", "High", "Medium", "Low"], weights)[0]
    sla = {"Critical": 15, "High": 30, "Medium": 60, "Low": 90}[severity]
    due = due or opened + d(sla)
    if closed == "auto":
        closed = opened + d(max(2, int(sla * rng.triangular(0.3, 2.8, 0.85) * (1.45 - 0.6 * h))))
        if closed > AS_OF:
            closed = None
    finding_id = next_id("fnd", "FND", 4)
    t["findings"].append(dict(
        finding_id=finding_id, system_id=system_id, control_id=control_id, severity=severity, source=source,
        source_test_id=test_id, title=title or f"{control['name']}: {rng.choice(ISSUES)}",
        opened_date=iso(opened), due_date=iso(due), closed_date=iso(closed), owner_id=owner_id))
    for n in range(rng.choice([1, 1, 2])):
        action_due = due - d(rng.randint(0, 7))
        completed = None
        if closed:
            completed = closed - d(rng.randint(0, 4))
        elif n == 0 and rng.random() < 0.3:
            completed = min(AS_OF, opened + d(rng.randint(3, 20)))
        t["remediation_actions"].append(dict(
            action_id=next_id("ra", "RA", 4), finding_id=finding_id, action=rng.choice(ACTIONS),
            owner_role=control["owner_role"], due_date=iso(action_due), completed_date=iso(completed)))
    return finding_id


def add_hero_story(t, next_id, event):
    """Hand-authored records for the connected scenario (Refund Resolution Agent)."""
    s = HERO
    owner = next(x["owner_id"] for x in t["ai_systems"] if x["system_id"] == s)
    t["findings"] = [f for f in t["findings"] if f["system_id"] != s]
    kept = {f["finding_id"] for f in t["findings"]}
    t["remediation_actions"] = [a for a in t["remediation_actions"] if a["finding_id"] in kept]

    def test(control_id, when, passed, line):
        add_test(t, next_id, s, control_id, when, passed, line, 0.93, owner, spawn=False)

    test("HUM-01", date(2026, 9, 10), False, "Second line")
    test("FIN-02", date(2026, 9, 28), True, "Second line")
    test("SEC-02", date(2026, 10, 6), True, "Second line")
    test("HUM-01", date(2026, 10, 6), True, "Second line")
    fail_id = next(x["test_id"] for x in t["control_tests"] if x["system_id"] == s and x["test_date"] == "2026-09-10")

    def finding(control_id, severity, source, title, opened, due, closed, actions, test_id=""):
        finding_id = next_id("fnd", "FND", 4)
        t["findings"].append(dict(finding_id=finding_id, system_id=s, control_id=control_id, severity=severity, source=source,
                                  source_test_id=test_id, title=title, opened_date=iso(opened), due_date=iso(due),
                                  closed_date=iso(closed), owner_id=owner))
        for action, role, action_due, completed in actions:
            t["remediation_actions"].append(dict(action_id=next_id("ra", "RA", 4), finding_id=finding_id, action=action,
                                                 owner_role=role, due_date=iso(action_due), completed_date=iso(completed)))

    finding("HUM-01", "Critical", "Incident", "Approval threshold circumvented by split refunds; no cumulative limit existed",
            date(2026, 9, 10), date(2026, 9, 25), date(2026, 10, 14), [
                ("Add cumulative per-customer limit and velocity alert (control FIN-02, rule AP-07b)", "Fraud operations", date(2026, 9, 24), date(2026, 9, 26)),
                ("Re-run adversarial test pack including split-transaction cases", "Security testing", date(2026, 10, 3), date(2026, 10, 6)),
                (f"Review the {HERO_REFUND_SUMMARY['customers']} affected customer accounts; confirm each refund was eligible and correct any that was not", "Operations control owner", date(2026, 9, 30), date(2026, 10, 10)),
            ], fail_id)
    finding("HUM-01", "Medium", "Second-line review", "Supervisor approval queue exceeded its 15-minute target during peak hours",
            date(2026, 10, 8), date(2026, 12, 7), None, [
                ("Add a second approver to the peak-hours rota and alert at 10 minutes", "Operations control owner", date(2026, 11, 20), None),
            ])

    for when, kind, actor, note in [
        (date(2025, 11, 10), "Registered", "System owner", "Use case entered in the AI inventory with purpose, owner and model."),
        (date(2025, 12, 4), "Risk assessed", "AI Risk (second line)", "Inherent tier Critical: autonomous action on customer accounts with restricted data."),
        (date(2025, 12, 18), "Controls selected", "Business unit risk lead", "23 controls required under policy v1.0; owners and evidence assigned."),
        (date(2026, 2, 12), "Release authorized", "AI Governance Committee", "Authorized with conditions: $150 autonomous limit, supervisor approval to $2,000, weekly sampling."),
        (date(2026, 3, 2), "Deployed", "System owner", "Live in customer chat for fee and service refunds."),
        (date(2026, 9, 9), "Incident detected", "Fraud operations", "INC-0031: reconciliation found several refunds to the same customers on the same day, each within the autonomous limit."),
        (date(2026, 9, 9), "Suspended", "Operations control owner", "Suspension authority exercised the same day; chat handed to representatives."),
        (date(2026, 9, 26), "Policy updated", "AI Risk (second line)", "Policy v1.1 adds control FIN-02 and rule AP-07b (cumulative daily limit per customer)."),
        (date(2026, 10, 6), "Controls retested", "Security testing", "Adversarial and approval-path retests passed, including split-refund cases."),
        (date(2026, 10, 20), "Reapproved with conditions", "AI Governance Committee", "Resume at reduced volume; cumulative limit active; 60-day review; open Medium finding tracked."),
        (date(2026, 10, 21), "Resumed", "System owner", "Agent returned to production under the reapproval conditions."),
    ]:
        event(s, when, kind, actor, note)


def add_incidents(t):
    live = [s for s in t["ai_systems"] if s["production_date"] and s["system_id"] != HERO]
    weights = [1 + 2 * s["f_autonomy"] + s["f_external_impact"] for s in live]
    rows = []

    def generic(start, end):
        s = rng.choices(live, weights)[0]
        low = max(start, date.fromisoformat(s["production_date"]))
        high = min(end, date.fromisoformat(s["retired_date"]) if s["retired_date"] else end)
        if low > high:
            return generic(start, end)
        category, _, text = rng.choices(INCIDENT_TYPES, [i[1] for i in INCIDENT_TYPES])[0]
        severity = rng.choices(SEVERITIES, [3, 14, 40, 43])[0]
        if category in ("Policy violation blocked", "Prompt injection attempt"):
            severity = rng.choice(["Sev3", "Sev4", "Sev4"])
        detected = between(low, high)
        resolved = detected + d(rng.randint(0, {"Sev1": 30, "Sev2": 24, "Sev3": 12, "Sev4": 4}[severity]))
        return dict(system_id=s["system_id"], detected_date=detected, category=category, severity=severity,
                    resolved_date=resolved if resolved <= AS_OF else None,
                    detection_source=rng.choice(["Automated monitoring", "Automated monitoring", "Employee report", "Customer complaint", "Control test"]),
                    customer_impact=int(category in ("Unauthorized action executed", "Sensitive data exposure") or (severity in ("Sev1", "Sev2") and rng.random() < 0.5)),
                    description=text)

    for _ in range(29):
        rows.append(generic(WINDOW_START, date(2026, 9, 8)))
    rows.append(dict(system_id=HERO, detected_date=date(2026, 6, 17), category="Prompt injection attempt", severity="Sev4",
                     resolved_date=date(2026, 6, 17), detection_source="Automated monitoring", customer_impact=0,
                     description="Customer message contained text instructing the agent to ignore refund limits. Rule AP-01 blocked it."))
    rows.sort(key=lambda r: r["detected_date"])
    rows.append(dict(system_id=HERO, detected_date=date(2026, 9, 9), category="Unauthorized action executed", severity="Sev2",
                     resolved_date=date(2026, 10, 14), detection_source="Control test", customer_impact=1,
                     description=(
                         "Daily reconciliation found {refunds} refunds to {customers} customers on {when}. Each refund was at or under the "
                         "${auto} autonomous limit, so none was reviewed by a supervisor. The refunds total ${total:,}. Every customer "
                         "received more than ${daily} that day; together that is ${above_daily:,} above ${daily} per customer per day, "
                         "the cumulative level policy v1.1 later set. No financial loss is established: these are amounts issued without review."
                     ).format(when=date.fromisoformat(HERO_REFUND_SUMMARY["day"]).strftime("%B %d, %Y").replace(" 0", " "), **HERO_REFUND_SUMMARY)))
    later = [generic(date(2026, 9, 10), AS_OF) for _ in range(12)]
    later.sort(key=lambda r: r["detected_date"])
    rows += later
    for i, r in enumerate(rows, 1):
        t["incidents"].append(dict(incident_id=f"INC-{i:04d}", system_id=r["system_id"], detected_date=iso(r["detected_date"]),
                                    category=r["category"], severity=r["severity"], resolved_date=iso(r["resolved_date"]),
                                    detection_source=r["detection_source"], customer_impact=r["customer_impact"], description=r["description"]))
    assert t["incidents"][30]["incident_id"] == HERO_INCIDENT and t["incidents"][30]["system_id"] == HERO
    t["incident_refunds"].extend(HERO_REFUNDS)


def add_model_changes(t, next_id, health):
    changes = [
        ("MDL-01", date(2026, 2, 10), "Minor version", "NL-4 Large maintenance release"),
        ("MDL-02", date(2026, 3, 18), "Minor version", "NL-4 Mini maintenance release"),
        ("MDL-06", date(2026, 4, 5), "Retrain", "Scheduled retrain of the fine-tuned model"),
        ("MDL-03", date(2026, 6, 15), "Terms change", "Provider revised data-retention terms"),
        ("MDL-07", date(2026, 7, 22), "Feature change", "Vendor enabled new AI features by default"),
        ("MDL-04", date(2026, 8, 20), "Deprecation notice", "Atlas XL end-of-support announced for Q1 2027"),
        ("MDL-01", date(2026, 9, 1), "Major version", "Provider moved NL-4 Large traffic to NL-5 Large"),
        ("MDL-02", date(2026, 9, 1), "Major version", "Provider moved NL-4 Mini traffic to NL-5 Mini"),
        ("MDL-06", date(2026, 10, 5), "Retrain", "Scheduled retrain of the fine-tuned model"),
    ]
    material = {"Major version", "Terms change", "Deprecation notice", "Retrain", "Feature change"}
    for model_id, when, kind, note in changes:
        for s in t["ai_systems"]:
            if s["model_id"] != model_id or not s["production_date"] or s["production_date"] > iso(when):
                continue
            if s["retired_date"] and s["retired_date"] <= iso(when):
                continue
            high = s["inherent_tier"] in ("High", "Critical")
            required = int(kind in material or high)
            due = completed = None
            if required:
                due = when + d(30 if high else 60)
                if s["system_id"] == HERO:
                    completed = when + d(12) if kind == "Minor version" else date(2026, 10, 6)
                elif rng.random() < 0.55 + 0.4 * health[s["system_id"]]:
                    completed = when + d(rng.randint(8, 75))
                    if completed > AS_OF:
                        completed = None
            t["model_changes"].append(dict(
                change_id=next_id("mc", "MC", 4), model_id=model_id, system_id=s["system_id"], change_date=iso(when),
                change_type=kind, change_note=note, reassessment_required=required,
                reassessment_due_date=iso(due), reassessment_completed_date=iso(completed)))


# ---------------------------------------------------------------- output
def write(tables):
    RAW.mkdir(parents=True, exist_ok=True)
    for name, rows in tables.items():
        with (RAW / f"{name}.csv").open("w", newline="", encoding="utf-8") as fh:
            writer = csv.DictWriter(fh, fieldnames=list(rows[0]), lineterminator="\n")
            writer.writeheader()
            writer.writerows(rows)
    meta = dict(
        organization="Larkmoor Financial Group (fictional)", as_of=iso(AS_OF), window_start=iso(WINDOW_START),
        history_start=iso(HISTORY_START), seed=SEED, hero_system=HERO, policy_version=policy["meta"]["version"],
        generator="analytics/generate_data.py",
        row_counts={name: len(rows) for name, rows in tables.items()},
        disclosure="Synthetic data generated by a seeded script. No real organization, person, vendor, incident or result is represented.")
    bundle = dict(meta=meta, tables={name: dict(columns=list(rows[0]), rows=[list(r.values()) for r in rows])
                                     for name, rows in tables.items()})
    data_dir = ROOT / "assets" / "data"
    data_dir.mkdir(parents=True, exist_ok=True)
    tail = "\nif (typeof module !== 'undefined') module.exports = (typeof window !== 'undefined' ? window : globalThis).%s;\n"
    (data_dir / "governance-data.js").write_text(
        "/* Generated by analytics/generate_data.py. Do not edit by hand. */\n(typeof window !== 'undefined' ? window : globalThis).GOV_DATA = "
        + json.dumps(bundle, separators=(",", ":")) + ";" + tail % "GOV_DATA", encoding="utf-8")
    (data_dir / "policy-data.js").write_text(
        "/* Generated from analytics/policy/policy_rules.json. Do not edit by hand. */\n(typeof window !== 'undefined' ? window : globalThis).GOV_POLICY = "
        + json.dumps(policy, separators=(",", ":")) + ";" + tail % "GOV_POLICY", encoding="utf-8")
    (RAW.parent / "dataset_meta.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
    return meta


if __name__ == "__main__":
    tables = build()
    meta = write(tables)
    print("Synthetic governance dataset written (seed %s, as of %s)" % (SEED, meta["as_of"]))
    for name, count in meta["row_counts"].items():
        print(f"  {name:22s}{count:6d}")
    tiers = {}
    for s in tables["ai_systems"]:
        tiers[s["inherent_tier"]] = tiers.get(s["inherent_tier"], 0) + 1
    print("  inherent tiers:", {k: tiers.get(k, 0) for k in TIERS})
