"""Weekly exception digest: rules decide, AI explains, a person approves.
Reads a CSV extract with columns: date, account_id, channel, type, amount.
Writes exceptions.csv and digest_prompt.txt. Uses synthetic or approved data only."""
import pandas as pd

LARGE = 5000          # flag single transactions at or above this amount
Z_LIMIT = 3.0         # flag amounts this many std devs above the account's history
df = pd.read_csv("transactions_sample.csv", parse_dates=["date"])
last_day = df["date"].max()
week = df[df["date"] > last_day - pd.Timedelta(days=7)].copy()
history = df[df["date"] <= last_day - pd.Timedelta(days=7)]

flags = []

# Rule 1: large single transactions
for _, r in week[week["amount"] >= LARGE].iterrows():
    flags.append((r["date"].date(), r["account_id"], "large_transaction",
                  f'{r["type"]} of {r["amount"]:.2f} via {r["channel"]}'))

# Rule 2: unusual for this account compared with its own history
stats = history.groupby("account_id")["amount"].agg(["mean", "std"])
for _, r in week.iterrows():
    if r["account_id"] in stats.index:
        m, s = stats.loc[r["account_id"]]
        if pd.notna(s) and s > 0 and (r["amount"] - m) / s >= Z_LIMIT:
            flags.append((r["date"].date(), r["account_id"], "unusual_for_account",
                          f'{r["amount"]:.2f} vs account average {m:.2f}'))

# Rule 3: possible duplicates (same account, day, type, amount)
dups = week[week.duplicated(["date", "account_id", "type", "amount"], keep=False)]
for (d, a, t, amt), _ in dups.groupby(["date", "account_id", "type", "amount"]):
    flags.append((d.date(), a, "possible_duplicate", f"{t} of {amt:.2f} appears more than once"))

out = pd.DataFrame(flags, columns=["date", "account_id", "rule", "detail"]).drop_duplicates()
out = out.sort_values(["date", "account_id", "rule"])
out.to_csv("exceptions.csv", index=False)

prompt = (
    "You are drafting a short weekly exception summary for a credit union "
    "operations manager. Use ONLY the rows below. Do not add facts, causes, "
    "or advice about specific people. Group by rule, give one plain sentence "
    "per group, and end with the question a reviewer should ask first.\n\n"
    + out.to_csv(index=False)
)
open("digest_prompt.txt", "w").write(prompt)
print(f"{len(out)} exceptions written to exceptions.csv")
print(out.groupby("rule").size().to_string())
