"""Pseudonymize a member extract before sharing it or using it in an analysis or AI tool.
Reads members.csv (synthetic or approved data only). Writes members_pseudonymized.csv.
The secret key comes from the environment, never from the code or the file."""
import os, sys, hmac, hashlib, datetime as dt
import pandas as pd

KEY = os.environ.get("PSEUDO_KEY", "").encode()
if len(KEY) < 16:
    sys.exit("Set PSEUDO_KEY to a long random secret (16+ characters) kept outside this folder.")
AS_OF = dt.date(2026, 11, 1)   # reference date for ages
K = 5                          # smallest group size allowed for the quasi-identifiers

def token(value, purpose="id"):
    """Keyed hash: same input and key give the same token. Without the key it cannot be recomputed."""
    return hmac.new(KEY, f"{purpose}|{value}".encode(), hashlib.sha256).hexdigest()

df = pd.read_csv("members.csv", dtype=str).drop_duplicates("member_id")
out = pd.DataFrame()
out["member_token"] = "M-" + df["member_id"].map(lambda v: token(v)[:16])

# Direct identifiers (name, email, phone, ssn_last4) are dropped, not hashed.
# Quasi-identifiers are generalized: age band instead of birth date, ZIP3 instead of ZIP.
age = df["dob"].map(lambda d: (AS_OF - dt.date.fromisoformat(d)).days // 365)
out["age_band"] = (age // 10 * 10).astype(str) + "s"
out["zip3"] = df["zip"].str[:3]
out["branch"] = df["branch"]

# Date shifting: each member gets a fixed offset of -30..+30 days, so intervals within a member survive.
def shifted(row):
    off = int(token(row["member_id"], "shift")[:8], 16) % 61 - 30
    return (dt.date.fromisoformat(row["join_date"]) + dt.timedelta(days=off)).isoformat()
out["join_date_shifted"] = df.apply(shifted, axis=1)

# k-anonymity check on the quasi-identifiers. Small groups are generalized step by step:
# first drop the branch, then the ZIP3, then the age band, until every group has at least K members.
qi = ["age_band", "zip3", "branch"]
def group_sizes():
    return out.groupby(qi)["member_token"].transform("size")
print(f"Rows in groups smaller than {K} before generalizing: {int((group_sizes() < K).sum())}")
for col in ["branch", "zip3", "age_band"]:
    small = group_sizes() < K
    if not small.any():
        break
    out.loc[small, col] = "*"
smallest = int(group_sizes().min())
print(f"Smallest group after generalizing: {smallest}")
if smallest < K:
    print("WARNING: some groups are still smaller than K. Do not release this file as is.")

out.to_csv("members_pseudonymized.csv", index=False)
print(f"{len(out)} rows written to members_pseudonymized.csv")
