#!/usr/bin/env python3
"""
netsuite_ai_audit.py - weekly review of changes made through the NetSuite AI Connector Service.

Agents Finance template based on Oracle NetSuite documentation (read 3 December 2026):
  - November monthly release 2026.2: "AI Client Identification in System Notes"
  - Viewing System Notes for Changes Made by AI Features
  - Connect to the NetSuite AI Connector Service: "NetSuite AI Connector Service (MCP) Execution Log"
    (21 days of data in production, 7 days in sandbox)

What it does (read-only, standard library only, no network, never connects to NetSuite):
  1. Reads a CSV export of System Notes rows (with the AI Used column) for the review period.
  2. Reads one or more CSV captures of the integration record's Execution Log > AI Connector Service (MCP) subtab.
  3. Reads a policy JSON (allowed AI clients, AI-enabled users, sensitive record types and fields).
  4. Writes a findings report (CSV + Markdown) and exits 1 if any HIGH finding remains.

Usage:
  python3 netsuite_ai_audit.py --self-test
  python3 netsuite_ai_audit.py --policy policy.json --system-notes notes.csv \
      --exec-log log-2026-11-24.csv log-2026-12-01.csv --out report

Licence: MIT-0 (no attribution required). Provided as is, without warranty.
"""
import argparse, csv, json, os, re, sys, tempfile
from datetime import datetime, timedelta

SEV_ORDER = {"HIGH": 0, "MEDIUM": 1, "INFO": 2}
DATE_FORMATS = ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d",
                "%m/%d/%Y %I:%M %p", "%m/%d/%Y %H:%M", "%d/%m/%Y %H:%M", "%m/%d/%Y"]


def parse_dt(value):
    v = (value or "").strip()
    for f in DATE_FORMATS:
        try:
            return datetime.strptime(v, f)
        except ValueError:
            pass
    raise ValueError(f"unrecognised date: {value!r} (use YYYY-MM-DD HH:MM)")


def norm(s):
    return re.sub(r"\s+", " ", (s or "").strip()).lower()


def read_csv(path):
    with open(path, newline="", encoding="utf-8-sig") as fh:
        rows = list(csv.DictReader(fh))
    return [{norm(k).replace(" ", "_"): (v or "").strip() for k, v in r.items()} for r in rows]


def capture_date(path, rows):
    if rows and rows[0].get("captured_on"):
        return parse_dt(rows[0]["captured_on"]).date()
    m = re.search(r"(\d{4}-\d{2}-\d{2})", os.path.basename(path))
    if not m:
        raise ValueError(f"{path}: add a captured_on column or a YYYY-MM-DD date to the file name")
    return datetime.strptime(m.group(1), "%Y-%m-%d").date()


def audit(policy, notes, captures):
    findings = []

    def add(sev, check, detail, ref=""):
        findings.append({"severity": sev, "check": check, "detail": detail, "reference": ref})

    env = policy.get("environment", "production")
    retention = 21 if env == "production" else 7
    start = parse_dt(policy["review_period"]["start"]).date()
    end = parse_dt(policy["review_period"]["end"]).date()
    allowed = [re.compile(p, re.I) for p in policy.get("allowed_client_patterns", [])]
    users = policy.get("ai_enabled_users", [])
    names = {norm(u["name"]): u for u in users}
    emails = {norm(u["email"]): u for u in users}
    sens_types = {norm(x) for x in policy.get("sensitive_record_types", [])}
    sens_fields = {norm(x) for x in policy.get("sensitive_fields", [])}
    role_types = {norm(x) for x in policy.get("permission_record_types", ["role", "manage roles"])}
    window = timedelta(minutes=int(policy.get("match_window_minutes", 10)))
    approvals = policy.get("approved_changes", [])

    def approved(ref):
        for a in approvals:
            if a.get("reference_contains") and a["reference_contains"] in ref:
                return a
        return None

    # --- 1. Execution log captures: retention gaps -------------------------------------------
    log_rows = []
    cap_dates = []
    for path, rows in captures:
        d = capture_date(path, rows)
        cap_dates.append(d)
        for r in rows:
            r["_dt"] = parse_dt(r.get("date") or r.get("date_and_time") or r.get("request_time"))
            log_rows.append(r)
    cap_dates = sorted(set(cap_dates))
    if not cap_dates:
        add("HIGH", "L1 log retention", f"No Execution Log capture for {start}..{end}. NetSuite keeps {retention} days in {env}; rows older than that are gone.")
    else:
        first_needed = start  # a capture on day X covers X-retention+1 .. X
        covered_from = cap_dates[0] - timedelta(days=retention - 1)
        if covered_from > first_needed:
            add("HIGH", "L1 log retention", f"First capture {cap_dates[0]} only reaches back to {covered_from}; calls from {first_needed} to {covered_from - timedelta(days=1)} are no longer in NetSuite.")
        for a, b in zip(cap_dates, cap_dates[1:]):
            if (b - a).days > retention - 1:
                lost_from = a + timedelta(days=1)
                lost_to = b - timedelta(days=retention)
                add("HIGH", "L1 log retention", f"Gap between captures {a} and {b} is {(b - a).days} days (> {retention - 1}); calls from {lost_from} to {lost_to} were not captured.")
        if cap_dates[-1] < end:
            add("MEDIUM", "L1 log retention", f"Last capture {cap_dates[-1]} is before the period end {end}; capture again before {cap_dates[-1] + timedelta(days=retention - 1)}.")

    # --- 2. Execution log content ---------------------------------------------------------------
    seen = set()
    fail_by_user = {}
    calls_by_user = {}
    for r in log_rows:
        key = (r["_dt"], r.get("user", ""), r.get("method", ""), r.get("url_path", r.get("path", "")))
        if key in seen:  # overlapping captures repeat rows
            continue
        seen.add(key)
        u = norm(r.get("user"))
        calls_by_user.setdefault(u, []).append(r["_dt"])
        if u and u not in emails:
            add("MEDIUM", "L2 unknown caller", f"{r.get('user')} called the AI Connector at {r['_dt']:%Y-%m-%d %H:%M} but is not in ai_enabled_users.", r.get("url_path", ""))
        status = norm(r.get("status"))
        code = r.get("http_status", "")
        if status not in ("success", "ok") or (code and not code.startswith("2")):
            fail_by_user[u] = fail_by_user.get(u, 0) + 1
    for u, n in sorted(fail_by_user.items()):
        if n >= int(policy.get("failure_alert", 5)):
            add("MEDIUM", "L3 repeated failures", f"{u}: {n} failed AI Connector calls in the captured log (permission errors or a client retrying).")
    flagged_unknown = {}
    for f in findings:
        if f["check"] == "L2 unknown caller":
            flagged_unknown.setdefault(f["detail"].split(" called")[0], []).append(f)
    # collapse repeated L2 rows to one per user
    findings = [f for f in findings if f["check"] != "L2 unknown caller"]
    for u, fs in flagged_unknown.items():
        add("MEDIUM", "L2 unknown caller", f"{u} made {len(fs)} AI Connector call(s) but is not in ai_enabled_users.")

    # --- 3. System Notes ---------------------------------------------------------------------------
    ai_rows = 0
    clients = {}
    for r in notes:
        dt = parse_dt(r.get("date") or r.get("date_time"))
        if not (start <= dt.date() <= end):
            continue
        ai = r.get("ai_used", "")
        rtype, field = norm(r.get("record_type")), norm(r.get("field") or r.get("object"))
        ref = f"{r.get('record_type')} {r.get('record_id')} {r.get('field') or r.get('object')} @ {dt:%Y-%m-%d %H:%M}"
        user = norm(r.get("user") or r.get("set_by"))
        if ai:
            ai_rows += 1
            clients[ai] = clients.get(ai, 0) + 1
            m = re.search(r"\((.*)\)", ai)
            client = m.group(1) if m else ""
            if ai.endswith("[...]") or ai.endswith("..."):
                add("MEDIUM", "A2 client truncated", f"AI Used value was shortened by NetSuite ({ai}); confirm the client from the Execution Log and the AI vendor's log.", ref)
            elif client and not any(p.search(client) for p in allowed):
                add("HIGH", "A2 unapproved client", f"Change made through {ai}; client is not in allowed_client_patterns.", ref)
            elif not client and ai.lower().startswith("ai connector"):
                add("INFO", "A2 no client string", "AI Used shows the connector without a client in brackets (change before the November 2026 release, or the client sent no usable User-Agent).", ref)
            if rtype in role_types:
                add("HIGH", "A5 AI changed permissions", f"{ai} changed a role or permission ({r.get('field') or r.get('object')}: {r.get('old_value')} -> {r.get('new_value')}).", ref)
            elif rtype in sens_types and approved(ref):
                ok = approved(ref)
                add("INFO", "A1 approved AI change", f"{ai} {r.get('action') or 'changed'} {r.get('field')}; approved by {ok.get('approver')} ({ok.get('evidence', 'no evidence noted')}).", ref)
            elif rtype in sens_types and (field in sens_fields or norm(r.get("action")) in ("create", "delete")):
                add("HIGH", "A1 AI changed a sensitive field", f"{ai} {r.get('action') or 'changed'} {r.get('field')}: {r.get('old_value')!r} -> {r.get('new_value')!r}. Needs a named approver.", ref)
            elif rtype in sens_types:
                add("MEDIUM", "A1 AI changed a finance record", f"{ai} changed {r.get('field')} on a sensitive record type.", ref)
            if user and user in names:
                email = norm(names[user]["email"])
                if not any(abs(t - dt) <= window for t in calls_by_user.get(email, [])):
                    add("MEDIUM", "A4 no matching log call", f"No Execution Log call by {names[user]['email']} within {window.seconds // 60} min of this change (capture gap, another integration record, or clock/time-zone mismatch).", ref)
            elif user:
                add("HIGH", "A3 AI change by unlisted user", f"{r.get('user')} made an AI-attributed change but is not in ai_enabled_users.", ref)
        else:
            ctx = norm(r.get("context"))
            if user in names and ctx and ctx not in ("ui", "user interface", "csv import"):
                add("MEDIUM", "A6 unattributed non-UI change", f"{r.get('user')} (AI-enabled) changed {r.get('field')} through context '{r.get('context')}' with AI Used empty: check whether a standard MCP tool or another integration made it.", ref)

    add("INFO", "Summary", f"{ai_rows} AI-attributed System Notes rows in {start}..{end}; clients: " + (", ".join(f"{k} x{v}" for k, v in sorted(clients.items())) or "none") + f"; {len(seen)} unique Execution Log calls from {len(cap_dates)} capture(s).")
    findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["check"], f["reference"]))
    return findings


def write_reports(findings, out):
    with open(out + ".csv", "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=["severity", "check", "detail", "reference"])
        w.writeheader()
        w.writerows(findings)
    counts = {s: sum(1 for f in findings if f["severity"] == s) for s in SEV_ORDER}
    verdict = "NO SIGN-OFF" if counts["HIGH"] else "READY FOR SIGN-OFF"
    with open(out + ".md", "w", encoding="utf-8") as fh:
        fh.write(f"# NetSuite AI Connector review: {verdict}\n\n")
        fh.write(f"HIGH {counts['HIGH']} · MEDIUM {counts['MEDIUM']} · INFO {counts['INFO']}\n\n")
        fh.write("| Severity | Check | Detail | Reference |\n|---|---|---|---|\n")
        for f in findings:
            fh.write("| {severity} | {check} | {d} | {reference} |\n".format(d=f["detail"].replace("|", "/"), **{k: v for k, v in f.items() if k != "detail"}))
        fh.write("\nReviewer: ____________________  Date: __________  Exceptions explained: yes / no\n")
    return counts, verdict


SAMPLE_POLICY = {
    "environment": "production",
    "review_period": {"start": "2026-11-02", "end": "2026-11-30"},
    "allowed_client_patterns": ["^example-claude/", "^openai-mcp/"],
    "ai_enabled_users": [
        {"name": "Ana Ruiz", "email": "ana.ruiz@example.com", "role": "AP Clerk - MCP read/draft"},
        {"name": "Tom Hale", "email": "tom.hale@example.com", "role": "Controller - MCP read only"}
    ],
    "sensitive_record_types": ["Journal Entry", "Vendor Bill", "Vendor Payment", "Vendor", "Customer Payment"],
    "sensitive_fields": ["Amount", "Account", "Approval Status", "Payment Hold", "Bank Account Number", "Posting Period", "Entity"],
    "permission_record_types": ["Role", "Manage Roles"],
    "approved_changes": [],
    "match_window_minutes": 10,
    "failure_alert": 5,
}

SAMPLE_NOTES = [
    # date, record_type, record_id, user, role, context, ai_used, action, field, old, new
    ("2026-11-10 09:12", "Vendor Bill", "VB-1042", "Ana Ruiz", "AP Clerk - MCP read/draft", "Web Services", "AI Connector Service (example-claude/1.0)", "Create", "Record", "", "Created"),
    ("2026-11-10 09:13", "Vendor Bill", "VB-1042", "Ana Ruiz", "AP Clerk - MCP read/draft", "Web Services", "AI Connector Service (example-claude/1.0)", "Set", "Memo", "", "Office lease Nov"),
    ("2026-11-12 15:40", "Journal Entry", "JE-2210", "Tom Hale", "Controller - MCP read only", "Web Services", "AI Connector Service (openai-mcp/1.0.0)", "Change", "Amount", "1,250.00", "12,500.00"),
    ("2026-11-14 11:05", "Customer", "C-88", "Tom Hale", "Controller - MCP read only", "Web Services", "AI Connector Service (openai-mcp/1.0.0)", "Change", "Comments", "", "Asked for remittance"),
    ("2026-11-18 08:30", "Vendor", "V-301", "Ana Ruiz", "AP Clerk - MCP read/draft", "Web Services", "AI Connector Service (my-agent-dev/0.3)", "Change", "Bank Account Number", "****1234", "****9876"),
    ("2026-11-20 10:00", "Role", "AP Clerk - MCP read/draft", "Tom Hale", "Controller - MCP read only", "Web Services", "AI Connector Service (openai-mcp/1.0.0)", "Change", "Permission: Vendor Payment", "None", "Full"),
    ("2026-11-21 16:45", "Vendor Bill", "VB-1077", "Ana Ruiz", "AP Clerk - MCP read/draft", "REST Web Services", "", "Change", "Approval Status", "Pending Approval", "Approved"),
    ("2026-11-24 09:02", "Customer Payment", "CP-551", "Sam Ortiz", "A/R Clerk", "Web Services", "AI Connector Service (example-claude/1.0)", "Change", "Memo", "", "Matched to INV-778"),
    ("2026-11-25 13:20", "Vendor Bill", "VB-1080", "Ana Ruiz", "AP Clerk - MCP read/draft", "Web Services", "AI Connector Service (example-claude/1.0 (compatible; very-long-agent-wrapper-name-for-finance-team-proxy) [...]", "Set", "Memo", "", "Utilities"),
    ("2026-11-26 10:10", "Vendor Bill", "VB-1081", "Ana Ruiz", "AP Clerk - MCP read/draft", "UI", "", "Change", "Approval Status", "Pending Approval", "Approved"),
]

ALL_CALLS = [
    ("2026-11-03 10:15", "0.5 s", "Success", "tom.hale@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-04 12:40", "0.6 s", "Success", "ana.ruiz@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-10 09:12", "0.8 s", "Success", "ana.ruiz@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-10 09:13", "0.6 s", "Success", "ana.ruiz@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-12 15:39", "1.1 s", "Success", "tom.hale@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-14 11:05", "0.7 s", "Success", "tom.hale@example.com", "200", "POST", "/services/mcp/v1/all"),
] + [("2026-11-15 22:0%d" % i, "0.2 s", "Failure", "pat.ng@example.com", "403", "POST", "/services/mcp/v1/all") for i in range(6)] + [
    ("2026-11-18 08:29", "0.9 s", "Success", "ana.ruiz@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-20 10:00", "0.5 s", "Success", "tom.hale@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-24 09:02", "0.6 s", "Success", "sam.ortiz@example.com", "200", "POST", "/services/mcp/v1/all"),
    ("2026-11-25 13:20", "0.7 s", "Success", "ana.ruiz@example.com", "200", "POST", "/services/mcp/v1/all"),
]


def capture_of(day, retention=21):
    """Rows NetSuite would still show on `day`: the last `retention` days, as in a real capture."""
    d = datetime.strptime(day, "%Y-%m-%d").date()
    return [r for r in ALL_CALLS
            if d - timedelta(days=retention - 1) <= datetime.strptime(r[0][:10], "%Y-%m-%d").date() <= d]


SAMPLE_LOGS = {"exec-log-2026-11-05.csv": capture_of("2026-11-05"), "exec-log-2026-11-30.csv": capture_of("2026-11-30")}

NOTE_HEAD = ["Date", "Record Type", "Record ID", "User", "Role", "Context", "AI Used", "Action", "Field", "Old Value", "New Value"]
LOG_HEAD = ["Date", "Duration", "Status", "User", "HTTP Status", "Method", "URL Path"]


def write_samples(folder):
    with open(os.path.join(folder, "policy.example.json"), "w", encoding="utf-8") as fh:
        json.dump(SAMPLE_POLICY, fh, indent=2)
        fh.write("\n")
    with open(os.path.join(folder, "system-notes.sample.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh); w.writerow(NOTE_HEAD); w.writerows(SAMPLE_NOTES)
    for name, rows in SAMPLE_LOGS.items():
        with open(os.path.join(folder, name), "w", newline="", encoding="utf-8") as fh:
            w = csv.writer(fh); w.writerow(LOG_HEAD); w.writerows(rows)


def run(policy_path, notes_path, log_paths, out):
    with open(policy_path, encoding="utf-8") as fh:
        policy = json.load(fh)
    notes = read_csv(notes_path)
    captures = [(p, read_csv(p)) for p in log_paths]
    findings = audit(policy, notes, captures)
    return write_reports(findings, out), findings


def self_test():
    tmp = tempfile.mkdtemp(prefix="ns-ai-audit-")
    write_samples(tmp)
    j = lambda n: os.path.join(tmp, n)
    (counts, verdict), findings = run(j("policy.example.json"), j("system-notes.sample.csv"),
                                      [j("exec-log-2026-11-05.csv"), j("exec-log-2026-11-30.csv")], j("report"))
    checks = {f["check"] for f in findings}
    expect = ["A1 AI changed a sensitive field", "A2 unapproved client", "A2 client truncated", "A3 AI change by unlisted user",
              "A5 AI changed permissions", "A6 unattributed non-UI change", "L1 log retention", "L2 unknown caller", "L3 repeated failures"]
    missing = [c for c in expect if c not in checks]
    ui_flagged = any("VB-1081" in f["reference"] for f in findings)
    assert not missing, f"self-test: expected checks missing: {missing}"
    assert not ui_flagged, "self-test: a UI edit was flagged"
    assert verdict == "NO SIGN-OFF"
    # after fixes: weekly captures, approved clients only, no AI writes on sensitive fields
    pol = dict(SAMPLE_POLICY)
    pol["approved_changes"] = [{"reference_contains": "VB-1042", "approver": "Tom Hale", "evidence": "AP approval log, 2026-11-10"}]
    clean_notes = [r for r in SAMPLE_NOTES if r[2] in ("VB-1042", "C-88", "VB-1081")]
    with open(j("notes-clean.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh); w.writerow(NOTE_HEAD); w.writerows(clean_notes)
    with open(j("policy-clean.json"), "w") as fh:
        json.dump(pol, fh)
    good_logs = []
    for d in ("2026-11-09", "2026-11-16", "2026-11-23", "2026-11-30"):
        with open(j(f"weekly-{d}.csv"), "w", newline="", encoding="utf-8") as fh:
            w = csv.writer(fh); w.writerow(LOG_HEAD); w.writerows([r for r in capture_of(d) if r[3] in ("ana.ruiz@example.com", "tom.hale@example.com")])
        good_logs.append(j(f"weekly-{d}.csv"))
    (counts2, verdict2), _ = run(j("policy-clean.json"), j("notes-clean.csv"), good_logs, j("report-clean"))
    assert counts2["HIGH"] == 0, counts2
    print(f"self-test OK in {tmp}")
    print(f"  sample data : {verdict} - HIGH {counts['HIGH']}, MEDIUM {counts['MEDIUM']}, INFO {counts['INFO']}")
    print(f"  after fixes : {verdict2} - HIGH {counts2['HIGH']}, MEDIUM {counts2['MEDIUM']}, INFO {counts2['INFO']}")
    return tmp


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--self-test", action="store_true")
    ap.add_argument("--write-samples", metavar="FOLDER")
    ap.add_argument("--policy")
    ap.add_argument("--system-notes")
    ap.add_argument("--exec-log", nargs="*", default=[])
    ap.add_argument("--out", default="netsuite-ai-review")
    a = ap.parse_args()
    if a.self_test:
        self_test(); return 0
    if a.write_samples:
        os.makedirs(a.write_samples, exist_ok=True); write_samples(a.write_samples); return 0
    if not (a.policy and a.system_notes):
        ap.error("--policy and --system-notes are required (or use --self-test)")
    (counts, verdict), _ = run(a.policy, a.system_notes, a.exec_log, a.out)
    print(f"{verdict}: HIGH {counts['HIGH']}, MEDIUM {counts['MEDIUM']}, INFO {counts['INFO']} -> {a.out}.md / {a.out}.csv")
    return 1 if counts["HIGH"] else 0


if __name__ == "__main__":
    sys.exit(main())
