#!/usr/bin/env python3
"""Claude use by department, from your own records.

Joins the Claude Enterprise Analytics API "users" export (one saved JSON answer per day) to your HR
file on the work email address, checks its own result, and writes three CSV files.

    python3 claude_use_by_department.py --hr hr.csv --days days          # the real thing
    python3 claude_use_by_department.py --make-demo demo                 # generated records, fixed seed
    python3 claude_use_by_department.py --make-demo demo-planted --plant-errors

Needs the duckdb Python module and nothing else. It never calls the network and never reads a key.
Everything it writes goes to --out (default: the folder this file is in).

Exit code 0: every check passed and the CSV files were written. Exit code 1: a check failed; the
failure is printed and no CSV is written. Claude users missing from the HR file are a finding (the
"Unmapped" department), not a failure.
"""
import argparse
import collections
import copy
import csv
import datetime as dt
import json
import pathlib
import random
import re
import sys

import duckdb

HR_FILE = "hr.csv"      # your HR file: one row per employee, including people who do not use Claude
DAYS_DIR = "days"       # the folder of saved day files: 2026-11-03.json, 2026-11-02.json, ...
WINDOW_DAYS = 30        # the period, ending on the export's last day
RECENT_DAYS = 7
MIN_GROUP = 5           # any count of fewer people than this shows "--" (a whole small department, or one cell)
UNMAPPED = "Unmapped"
REQUIRED = ("email", "department", "manager_email")
PRODUCTS = ("chat", "claude_code", "cowork", "office", "design")
MEASURES = ("messages", "conversations", "code_sessions", "cowork_sessions", "office_sessions",
            "design_sessions")
DAY_FILE = re.compile(r"^(\d{4}-\d{2}-\d{2})(?:-(\d+))?\.json$")  # 2026-11-03.json, 2026-11-03-2.json
OFFICE_APPS = ("excel", "outlook", "powerpoint", "word")


def norm(s):
    """Matching ignores case and surrounding spaces."""
    return (s or "").strip().lower()


def num(d, *path):
    """A number from a nested field; a missing field, null or non-number counts as 0."""
    for k in path:
        if not isinstance(d, dict):
            return 0
        d = d.get(k)
    return d if isinstance(d, (int, float)) and not isinstance(d, bool) else 0


# ---------------------------------------------------------------- reading the inputs
def read_hr(path):
    """Returns (header, rows, error). Each row: data row number, normalized email, department, manager."""
    try:
        with open(path, newline="", encoding="utf-8-sig") as f:
            table = [r for r in csv.reader(f) if any(c.strip() for c in r)]
    except (OSError, UnicodeDecodeError) as e:
        return [], [], f"cannot read {path}: {e.__class__.__name__}"
    if not table:
        return [], [], f"{path} is empty"
    header = [h.strip().lower() for h in table[0]]
    rows = []
    if all(c in header for c in REQUIRED):
        ix = {c: header.index(c) for c in REQUIRED}
        for n, r in enumerate(table[1:], start=1):
            get = lambda c: r[ix[c]].strip() if ix[c] < len(r) else ""
            rows.append({"row": n, "email": norm(get("email")) or None,
                         "department": get("department"), "manager": norm(get("manager_email")) or None})
    return header, rows, None


def read_days(folder):
    """Returns pages {(day, page): {file, data, next_page}}, duplicates, unreadable, ignored."""
    pages, dupes, unreadable, ignored = {}, [], [], []
    folder = pathlib.Path(folder)
    if not folder.is_dir():
        return pages, dupes, [f"{folder} is not a folder"], ignored
    for p in sorted(folder.iterdir()):
        m = DAY_FILE.match(p.name)
        if not m:
            ignored.append(p.name)
            continue
        key = (dt.date.fromisoformat(m.group(1)), int(m.group(2) or 1))
        if key in pages:
            dupes.append(p.name)
            continue
        try:
            body = json.loads(p.read_text(encoding="utf-8"))
            if not isinstance(body, dict) or not isinstance(body.get("data"), list):
                raise ValueError("no data list")
            pages[key] = {"file": p.name, "data": body["data"], "next_page": body.get("next_page")}
        except (OSError, ValueError) as e:  # JSONDecodeError and UnicodeDecodeError are ValueErrors
            unreadable.append(f"{p.name} ({e.__class__.__name__})")
    return pages, dupes, unreadable, ignored


# ---------------------------------------------------------------- the checks
class Report:
    def __init__(self):
        self.lines, self.failed = [], 0

    def check(self, name, ok, detail):
        self.failed += 0 if ok else 1
        self.lines.append(f"  [{'PASS' if ok else 'FAIL'}] {name}: {detail}")


def hr_checks(rep, header, rows, error):
    missing = [c for c in REQUIRED if c not in header]
    rep.check("HR file has the three required columns", not missing and not error,
              error or ("missing " + ", ".join(missing) if missing else
                        f"email, department, manager_email found among {len(header)} columns"))
    if missing or error:
        for name in ("no email appears twice in the HR file", "every manager_email is an email in the HR file"):
            rep.check(name, False, "not run: the HR file could not be read")
        return
    count = collections.Counter(r["email"] for r in rows if r["email"])
    dup = sorted(e for e, n in count.items() if n > 1)
    blank = [r["row"] for r in rows if not r["email"]]
    rep.check("no email appears twice in the HR file", not dup and not blank,
              f"{len(dup)} email(s) on more than one row, {len(blank)} row(s) with a blank email"
              + (f"; data rows {sorted(r['row'] for r in rows if r['email'] in dup)[:5]}" if dup else ""))
    emails = set(count)
    orphans = [r["row"] for r in rows if r["manager"] and r["manager"] not in emails]
    blanks = [r["row"] for r in rows if not r["manager"]]
    rep.check("every manager_email is an email in the HR file", not orphans and len(blanks) <= 1,
              f"{len(orphans)} manager(s) not in the file, {len(blanks)} blank manager_email (at most 1 allowed)"
              + (f"; data rows {orphans[:5]}" if orphans else ""))


def day_checks(rep, pages, dupes, unreadable, args):
    present = sorted({d for d, _ in pages})
    # a day file that is present but unreadable still counts toward the newest day, so a broken
    # newest file fails the readable check instead of silently moving the window a day earlier
    named = present + [dt.date.fromisoformat(m.group(1)) for m in
                       (DAY_FILE.match(u.split(" ")[0]) for u in unreadable) if m]
    last = dt.date.fromisoformat(args.last_day) if args.last_day else (max(named) if named else None)
    if last is None:
        rep.check("every day file is readable and not empty", False, "no day files found in " + str(args.days))
        rep.check("every day in the range is present exactly once", False, "no day files found")
        return [], None, None
    first = last - dt.timedelta(days=WINDOW_DAYS - 1)
    days = [first + dt.timedelta(days=i) for i in range(WINDOW_DAYS)]
    in_range = {k: v for k, v in pages.items() if first <= k[0] <= last}
    empty = [v["file"] for v in in_range.values() if not v["data"]]
    bad_rec = sum(1 for v in in_range.values() for r in v["data"]
                  if not (isinstance(r, dict) and isinstance(r.get("user"), dict)
                          and (r["user"].get("id") or r["user"].get("email_address"))))
    unread = [u for u in unreadable if not (DAY_FILE.match(u.split(" ")[0])
              and not first <= dt.date.fromisoformat(DAY_FILE.match(u.split(" ")[0]).group(1)) <= last)]
    rep.check("every day file is readable and not empty", not unread and not empty and not bad_rec,
              f"{len(unread)} unreadable, {len(empty)} empty, {bad_rec} record(s) without a user"
              + (f"; {', '.join((unread + empty)[:3])}" if unread or empty else ""))
    missing = [d.isoformat() for d in days if (d, 1) not in in_range]
    gaps = [f"{d.isoformat()} page {p}" for (d, p), v in in_range.items()
            if v["next_page"] and (d, p + 1) not in in_range]
    rep.check("every day in the range is present exactly once", not missing and not dupes and not gaps,
              f"{WINDOW_DAYS - len(missing)} of {WINDOW_DAYS} days present from {first} to {last}"
              + (f"; missing {', '.join(missing[:5])}" if missing else "")
              + (f"; duplicate file {', '.join(dupes[:3])}" if dupes else "")
              + (f"; next page missing for {', '.join(gaps[:3])}" if gaps else ""))
    return days, first, last


def load_activity(pages, first, last):
    """Flatten the in-range records into rows, adding up the export's own totals on the way."""
    rows, totals = [], dict.fromkeys(MEASURES, 0)
    for (day, page), v in sorted(pages.items()):
        if not first <= day <= last:
            continue
        for i, r in enumerate(v["data"], start=1):
            if not (isinstance(r, dict) and isinstance(r.get("user"), dict)):
                continue
            email = norm(r["user"].get("email_address")) or None
            uid = str(r["user"].get("id") or "").strip() or f"email:{email}"
            office = sum(num(r, "office_metrics", a, "distinct_session_count") for a in OFFICE_APPS)
            vals = (
                num(r, "chat_metrics", "message_count") + num(r, "chat_cowork_unified_metrics", "chat", "message_count"),
                num(r, "chat_metrics", "distinct_conversation_count")
                + num(r, "chat_cowork_unified_metrics", "chat", "distinct_conversation_count"),
                num(r, "claude_code_metrics", "core_metrics", "distinct_session_count"),
                num(r, "cowork_metrics", "distinct_session_count")
                + num(r, "chat_cowork_unified_metrics", "sessions", "distinct_session_count"),
                office,
                num(r, "design_metrics", "distinct_session_count"),
            )
            for k, x in zip(MEASURES, vals):
                totals[k] += x
            rows.append((day, v["file"], i, uid, email, *vals))
    return rows, totals


def duplicate_users(rows):
    seen, dup = collections.Counter(), []
    for day, f, i, uid, *_ in rows:
        seen[(day, uid)] += 1
        if seen[(day, uid)] == 2:
            dup.append(f"{f} record {i}")
    return dup


# ---------------------------------------------------------------- the join and the counts
def department_names(hr_rows):
    """Department names match ignoring case and surrounding spaces ('Sales' and 'sales ' are one
    department, shown in its most common spelling). A blank department goes to Unmapped."""
    spellings = collections.defaultdict(collections.Counter)
    for r in hr_rows:
        if norm(r["department"]):
            spellings[norm(r["department"])][r["department"].strip()] += 1
    shown = {k: sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] for k, c in spellings.items()}
    return lambda name: shown.get(norm(name), UNMAPPED)


def analyze(con, hr_rows, act_rows, last):
    dept = department_names(hr_rows)
    con.execute("CREATE TABLE hr(row_no INT, email VARCHAR, department VARCHAR, manager VARCHAR)")
    con.executemany("INSERT INTO hr VALUES (?,?,?,?)",
                    [(r["row"], r["email"], dept(r["department"]), r["manager"]) for r in hr_rows])
    con.execute("""CREATE TABLE activity(day DATE, file VARCHAR, rec INT, user_id VARCHAR, email VARCHAR,
                   messages BIGINT, conversations BIGINT, code_sessions BIGINT, cowork_sessions BIGINT,
                   office_sessions BIGINT, design_sessions BIGINT)""")
    con.executemany("INSERT INTO activity VALUES (?,?,?,?,?,?,?,?,?,?,?)", act_rows)
    # one row per Claude user id: the email on its latest day, matched to the HR file. A person is
    # their HR email when matched (two user ids with one HR email are one person), else the user id.
    con.execute("""CREATE TABLE ud AS
        SELECT u.user_id, u.email, h.email AS hr_email, coalesce(h.department, ?) AS department,
               coalesce(h.email, 'id:' || u.user_id) AS person
        FROM (SELECT user_id, arg_max(email, day) AS email FROM activity GROUP BY user_id) u
        LEFT JOIN hr h ON h.email = u.email""", [UNMAPPED])
    con.execute("""CREATE TABLE per_user AS
        SELECT d.person, min(d.hr_email) AS email, d.department,
               sum(a.messages) AS messages, sum(a.conversations) AS conversations,
               sum(a.code_sessions) AS code_sessions, sum(a.cowork_sessions) AS cowork_sessions,
               sum(a.office_sessions) AS office_sessions, sum(a.design_sessions) AS design_sessions,
               max(CASE WHEN a.day > ? AND a.messages + a.code_sessions + a.cowork_sessions
                        + a.office_sessions + a.design_sessions > 0 THEN 1 ELSE 0 END) AS act7,
               max(CASE WHEN a.messages + a.code_sessions + a.cowork_sessions
                        + a.office_sessions + a.design_sessions > 0 THEN 1 ELSE 0 END) AS act30
        FROM ud d JOIN activity a USING (user_id)
        GROUP BY d.person, d.department""", [last - dt.timedelta(days=RECENT_DAYS)])
    return con.execute("""
        WITH depts AS (SELECT DISTINCT department FROM hr UNION SELECT ?),
        ppl AS (SELECT department, count(*) AS people FROM hr GROUP BY department),
        use AS (SELECT department, count(*) AS claude_users, sum(act7) AS active_7d, sum(act30) AS active_30d,
                       sum(messages) AS messages, sum(conversations) AS conversations,
                       sum(code_sessions) AS code_sessions, sum(cowork_sessions) AS cowork_sessions,
                       sum(office_sessions) AS office_sessions, sum(design_sessions) AS design_sessions,
                       sum(CAST(messages > 0 AS INT)) AS users_chat, sum(CAST(code_sessions > 0 AS INT)) AS users_code,
                       sum(CAST(cowork_sessions > 0 AS INT)) AS users_cowork,
                       sum(CAST(office_sessions > 0 AS INT)) AS users_office,
                       sum(CAST(design_sessions > 0 AS INT)) AS users_design
                FROM per_user GROUP BY department)
        SELECT d.department, coalesce(p.people, 0), coalesce(u.claude_users, 0), coalesce(u.active_7d, 0),
               coalesce(u.active_30d, 0), coalesce(u.messages, 0), coalesce(u.conversations, 0),
               coalesce(u.code_sessions, 0), coalesce(u.cowork_sessions, 0), coalesce(u.office_sessions, 0),
               coalesce(u.design_sessions, 0), coalesce(u.users_chat, 0), coalesce(u.users_code, 0),
               coalesce(u.users_cowork, 0), coalesce(u.users_office, 0), coalesce(u.users_design, 0)
        FROM depts d LEFT JOIN ppl p USING (department) LEFT JOIN use u USING (department)
        ORDER BY (d.department = ?), d.department""", [UNMAPPED, UNMAPPED]).fetchall()


COLS = ("department", "people", "claude_users", "active_7d", "active_30d", "messages", "conversations",
        "code_sessions", "cowork_sessions", "office_sessions", "design_sessions",
        "users_chat", "users_code", "users_cowork", "users_office", "users_design")


PRODUCT_CELLS = (("users_chat", ("messages", "conversations")), ("users_code", ("code_sessions",)),
                 ("users_cowork", ("cowork_sessions",)), ("users_office", ("office_sessions",)),
                 ("users_design", ("design_sessions",)))


def few(n):
    """A count of 1 to MIN_GROUP-1 people, small enough to point at someone."""
    return isinstance(n, int) and 0 < n < MIN_GROUP


def shaped(rows):
    """Dicts with '--' wherever a number would describe fewer than MIN_GROUP people (not Unmapped):
    every count of a department under MIN_GROUP people; every usage count of a department with 1 to
    MIN_GROUP-1 Claude users; an active count of 1 to MIN_GROUP-1 (and its share); and a product's
    people and amounts when 1 to MIN_GROUP-1 people used it."""
    out = []
    for r in rows:
        d = dict(zip(COLS, r))
        d["share"] = ("n/a" if d["people"] == 0 else f"{100 * d['active_30d'] / d['people']:.1f}")
        hide = set()
        if d["department"] != UNMAPPED:
            if d["people"] < MIN_GROUP:
                hide = set(d) - {"department"}
            elif few(d["claude_users"]):
                hide = set(d) - {"department", "people"}
            else:
                hide |= {"active_7d"} if few(d["active_7d"]) else set()
                hide |= {"active_30d", "share"} if few(d["active_30d"]) else set()
                for users, amounts in PRODUCT_CELLS:
                    if few(d[users]):
                        hide |= {users, *amounts}
        d = {k: ("--" if k in hide else v) for k, v in d.items()}
        out.append(d)
    return out


def show(rows):
    head = ["Department", "People", "Users", "Active 7d", "Active 30d", "Active %", "Messages", "Conversations"]
    keys = ["department", "people", "claude_users", "active_7d", "active_30d", "share", "messages", "conversations"]
    body = [[str(d[k]) for k in keys] for d in rows]
    w = [max(len(x) for x in col) for col in zip(head, *body)]
    fmt = lambda cells: "  ".join(c.ljust(w[0]) if i == 0 else c.rjust(w[i]) for i, c in enumerate(cells))
    print(fmt(head))
    for b in body:
        print(fmt(b))


def show_products(rows):
    head = ["Department", "Chat", "Claude Code", "Cowork", "Office", "Design"]
    body = []
    for d in rows:
        cell = lambda u, m: "--" if "--" in (d[u], d[m]) else f"{d[u]}/{d[m]}"
        body.append([d["department"], cell("users_chat", "messages"), cell("users_code", "code_sessions"),
                     cell("users_cowork", "cowork_sessions"), cell("users_office", "office_sessions"),
                     cell("users_design", "design_sessions")])
    w = [max(len(x) for x in col) for col in zip(head, *body)]
    fmt = lambda cells: "  ".join(c.ljust(w[0]) if i == 0 else c.rjust(w[i]) for i, c in enumerate(cells))
    print(fmt(head))
    for b in body:
        print(fmt(b))


def write_outputs(out, rows, unmapped):
    out = pathlib.Path(out)
    out.mkdir(parents=True, exist_ok=True)
    with open(out / "claude_use_by_department.csv", "w", newline="", encoding="utf-8-sig") as f:
        w = csv.writer(f)
        w.writerow(["department", "people_in_hr_file", "claude_users", "active_7_days", "active_30_days",
                    "share_active_30_days_pct", "messages", "conversations", "claude_code_sessions",
                    "cowork_sessions", "office_sessions", "design_sessions"])
        for d in rows:
            w.writerow([d["department"], d["people"], d["claude_users"], d["active_7d"], d["active_30d"],
                        d["share"], d["messages"], d["conversations"], d["code_sessions"],
                        d["cowork_sessions"], d["office_sessions"], d["design_sessions"]])
    units = (("chat", "messages", "users_chat", "messages"),
             ("claude_code", "sessions", "users_code", "code_sessions"),
             ("cowork", "sessions", "users_cowork", "cowork_sessions"),
             ("office", "sessions", "users_office", "office_sessions"),
             ("design", "sessions", "users_design", "design_sessions"))
    with open(out / "claude_use_by_product.csv", "w", newline="", encoding="utf-8-sig") as f:
        w = csv.writer(f)
        w.writerow(["department", "product", "unit", "people_using_in_30_days", "amount_in_30_days"])
        for d in rows:
            for product, unit, users, amount in units:
                w.writerow([d["department"], product, unit, d[users], d[amount]])
    with open(out / "claude_unmapped_users.csv", "w", newline="", encoding="utf-8-sig") as f:
        w = csv.writer(f)
        w.writerow(["file", "record_in_file", "anthropic_user_id", "email_address"])
        w.writerows(unmapped)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--hr", default=HR_FILE, help="the HR file (default: HR_FILE at the top of the script)")
    ap.add_argument("--days", default=DAYS_DIR, help="the folder of saved day files (default: DAYS_DIR)")
    ap.add_argument("--out", default=str(pathlib.Path(__file__).resolve().parent),
                    help="where the CSV files go (default: this script's folder)")
    ap.add_argument("--last-day", help="YYYY-MM-DD: end the 30 days here instead of at the newest file")
    ap.add_argument("--make-demo", metavar="FOLDER", help="write generated records to FOLDER and stop")
    ap.add_argument("--plant-errors", action="store_true", help="with --make-demo: plant five errors for the checks to catch")
    args = ap.parse_args(argv)
    if args.make_demo:
        return make_demo(pathlib.Path(args.make_demo), args.plant_errors)

    hr_header, hr_rows, hr_error = read_hr(args.hr)
    pages, dupes, unreadable, ignored = read_days(args.days)
    print(f"HR file: {args.hr} ({len(hr_rows)} rows)   Day files: {args.days} ({len(pages)} read"
          + (f", {len(ignored)} ignored" if ignored else "") + ")\n")
    rep = Report()
    hr_checks(rep, hr_header, hr_rows, hr_error)
    days, first, last = day_checks(rep, pages, dupes, unreadable, args)
    act_rows, totals = load_activity(pages, first, last) if first else ([], dict.fromkeys(MEASURES, 0))
    dup = duplicate_users(act_rows)
    rep.check("no Claude user appears twice on the same day", not dup,
              f"{len(dup)} user(s) twice on a day" + (f"; first at {dup[0]}" if dup else ""))
    rows = []
    if act_rows:
        con = duckdb.connect()
        rows = analyze(con, hr_rows, act_rows, last)
        got = {k: sum(r[5 + j] for r in rows) for j, k in enumerate(MEASURES)}
        off = [f"{k} {got[k]} vs {totals[k]}" for k in MEASURES if got[k] != totals[k]]
        rep.check("department totals equal the export's own totals", not off,
                  "all six measures agree" if not off else "; ".join(off))
    else:
        rep.check("department totals equal the export's own totals", False, "no activity rows to total")
    print("Checks")
    print("\n".join(rep.lines))

    if rows:
        unmapped = con.execute("""SELECT a.file, a.rec, a.user_id, coalesce(a.email, '') FROM activity a
            JOIN ud d USING (user_id) WHERE d.department = ? QUALIFY row_number() OVER
            (PARTITION BY a.user_id ORDER BY a.day, a.file, a.rec) = 1 ORDER BY a.user_id""", [UNMAPPED]).fetchall()
        users, matched, shared = con.execute("""SELECT count(DISTINCT person),
            count(DISTINCT CASE WHEN department <> ? THEN hr_email END),
            count(DISTINCT user_id) - count(DISTINCT person) FROM ud""", [UNMAPPED]).fetchone()
        idle = con.execute("""SELECT count(*) FROM hr WHERE NOT EXISTS (SELECT 1 FROM per_user p
            WHERE p.act30 = 1 AND p.email = hr.email)""").fetchone()[0]
        print("\nMatch report")
        print(f"  Claude users in the export:  {users}")
        print(f"  matched to the HR file:      {matched}")
        print(f"  unmapped (department '{UNMAPPED}'): {len(unmapped)}")
        print(f"  HR rows with no Claude activity in the {WINDOW_DAYS} days: {idle} of {len(hr_rows)}")
        print(f"  extra Claude user ids for a person already counted: {shared}")
    if rep.failed:
        print(f"\n{rep.failed} CHECK(S) FAILED: no tables shown, no CSV written")
        return 1
    data = shaped(rows)
    print(f"\nUse by department, {first} to {last} (-- hides any count of fewer than {MIN_GROUP} people)")
    show(data)
    print("\nUse by product: people who used it / amount (chat counts messages, the others count sessions)")
    show_products(data)
    write_outputs(args.out, data, unmapped)
    print(f"\nAll checks passed. Wrote claude_use_by_department.csv, claude_use_by_product.csv and "
          f"claude_unmapped_users.csv (next to the script, or in --out)")
    return 0


# ---------------------------------------------------------------- generated records
FIRST_NAMES = ("ada alder bram cora dale edda finn gwen hale iris jory kira lars mira noel odin pera quin "
               "rhea sven tara ulla vera wren xena yara zeke amos beck cleo dara eben fern gale hana ivor "
               "jett kell lena milo").split()
LAST_NAMES = ("ashby barlow carver dunmore ellery fenwick garrow hartley ingram jarvis kemble lowell "
              "marlow norwood oakley pryor quill ravel sutter thorne upton vance whitlock yardley zeller "
              "abbott birch calloway dorsey easton farrow granger holloway irving jessup keane lambert "
              "mercer nolan").split()
# name, people, share with a seat who use it, intensity, mix over (chat, claude_code, cowork, office, design)
DEMO_DEPARTMENTS = (
    ("Executive Office", 3, 0.7, "low", (0.8, 0.0, 0.1, 0.1, 0.0)),
    ("Engineering", 62, 0.95, "high", (0.3, 0.6, 0.08, 0.0, 0.02)),
    ("Product", 18, 0.9, "medium", (0.5, 0.1, 0.2, 0.1, 0.1)),
    ("Data and Analytics", 20, 0.9, "high", (0.4, 0.4, 0.1, 0.1, 0.0)),
    ("Sales", 48, 0.7, "medium", (0.6, 0.0, 0.1, 0.3, 0.0)),
    ("Marketing", 30, 0.85, "high", (0.5, 0.0, 0.1, 0.15, 0.25)),
    ("Customer Support", 44, 0.6, "low", (1.0, 0.0, 0.0, 0.0, 0.0)),
    ("Operations", 26, 0.6, "medium", (0.6, 0.0, 0.1, 0.3, 0.0)),
    ("Finance", 22, 0.55, "low", (0.5, 0.0, 0.0, 0.5, 0.0)),
    ("People", 14, 0.5, "low", (0.7, 0.0, 0.0, 0.3, 0.0)),
    ("Legal", 7, 0.4, "low", (1.0, 0.0, 0.0, 0.0, 0.0)),
    ("Internal Audit", 4, 0.5, "low", (0.8, 0.0, 0.0, 0.2, 0.0)),
)
DEMO_LAST_DAY = dt.date(2026, 11, 3)
PLANTED_EMAIL = "contractor.planted@example.com"


def demo_record(uid, email, rng, chat=0, convs=0, code=0, cowork=0, office=0, design=0):
    """One record shaped like the reference's, with only the fields this script reads (and their
    siblings the reference lists for chat), all other products zero."""
    apps = {a: {"distinct_session_count": 0, "message_count": 0} for a in OFFICE_APPS}
    if office:
        apps[rng.choice(OFFICE_APPS)]["distinct_session_count"] = office
    return {
        "user": {"type": "user", "id": uid, "email_address": email},
        "chat_metrics": {"message_count": chat, "distinct_conversation_count": convs},
        "claude_code_metrics": {"core_metrics": {"distinct_session_count": code}},
        "cowork_metrics": {"message_count": 0, "distinct_session_count": cowork},
        "office_metrics": apps,
        "design_metrics": {"message_count": 0, "distinct_session_count": design},
    }


def make_demo(folder, plant):
    """An invented company: people at example.com addresses, a fixed seed (54), 30 days."""
    rng = random.Random(54)
    (folder / "days").mkdir(parents=True, exist_ok=True)
    used, hr, ceo = set(), [], None

    def new_email():
        base = f"{rng.choice(FIRST_NAMES)}.{rng.choice(LAST_NAMES)}"
        email, n = f"{base}@example.com", 1
        while email in used:
            n += 1
            email = f"{base}{n}@example.com"
        used.add(email)
        return email

    profiles = {}
    for name, size, adopt, level, mix in DEMO_DEPARTMENTS:
        head = None
        for i in range(size):
            email = new_email()
            if ceo is None:
                ceo, manager = email, ""
            else:
                manager = ceo if i == 0 or name == "Executive Office" else head
            if i == 0:
                head = email
            hr.append({"email": email, "department": name, "manager_email": manager,
                       "location": rng.choice(("Remote", "Austin", "Denver", "Chicago")),
                       "role": "Head" if i == 0 else rng.choice(("Specialist", "Analyst", "Manager", "Lead")),
                       "hire_date": (dt.date(2015, 1, 1) + dt.timedelta(days=rng.randint(0, 4000))).isoformat(),
                       "cost_center": "CC-" + name[:3].upper()})
            profiles[email] = (adopt, level, mix)
    first = DEMO_LAST_DAY - dt.timedelta(days=WINDOW_DAYS - 1)
    day_list = [first + dt.timedelta(days=i) for i in range(WINDOW_DAYS)]
    seats = []
    for h in hr:
        if h["email"] == ceo or rng.random() < 0.88:
            adopter = rng.random() < profiles[h["email"]][0]
            rate = {"high": 0.8, "medium": 0.55, "low": 0.3}[profiles[h["email"]][1]] * rng.uniform(0.5, 1.2)
            seats.append((h["email"], "user_" + "".join(rng.choices("0123456789abcdef", k=12)), adopter,
                          min(rate, 0.95), profiles[h["email"]][2]))
    days = {}
    for day in day_list:
        weekend = day.weekday() >= 5
        recs = []
        for email, uid, adopter, rate, mix in seats:
            v = dict.fromkeys(("chat", "convs", "code", "cowork", "office", "design"), 0)
            if adopter and rng.random() < rate * (0.15 if weekend else 1.0):
                used_now = {rng.choices(PRODUCTS, weights=mix)[0]}
                used_now |= {p for p, w in zip(PRODUCTS, mix) if rng.random() < w * 0.5}
                if "chat" in used_now:
                    v["chat"] = rng.randint(3, 40)
                    v["convs"] = max(1, v["chat"] // rng.randint(4, 8))
                for p, key in (("claude_code", "code"), ("cowork", "cowork"), ("office", "office"),
                               ("design", "design")):
                    if p in used_now:
                        v[key] = rng.randint(1, 4)
            recs.append(demo_record(uid, email, rng, v["chat"], v["convs"], v["code"], v["cowork"],
                                    v["office"], v["design"]))
        days[day] = sorted(recs, key=lambda r: r["user"]["email_address"])

    planted = []
    if plant:
        hr.append(dict(hr[10]))
        planted.append(f"one HR row repeated (HR data row {len(hr)} copies row 11)")
        gone = "nobody.here@example.com"
        if gone in used:
            raise SystemExit("could not plant a manager who is not in the file")
        hr[20]["manager_email"] = gone
        planted.append("manager_email on HR data row 21 is not in the file")
        missing_day = day_list[15]
        if missing_day not in days:
            raise SystemExit("could not plant a missing day")
        del days[missing_day]
        planted.append(f"day file for {missing_day} removed")
        twice = day_list[22]
        days[twice].append(copy.deepcopy(days[twice][5]))
        planted.append(f"one record repeated on {twice}")
        if PLANTED_EMAIL in used:
            raise SystemExit("could not plant a Claude user who is not in the HR file")
        for day in day_list[-3:]:
            days[day].append(demo_record("user_planted000001", PLANTED_EMAIL, rng, chat=12, convs=2))
        planted.append("a Claude user whose email is not in the HR file, on the last 3 days")

    with open(folder / "hr.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(hr[0]))
        w.writeheader()
        w.writerows(hr)
    for day, recs in days.items():
        (folder / "days" / f"{day}.json").write_text(json.dumps({"data": recs, "next_page": None},
                                                               separators=(",", ":")), encoding="utf-8")
    print(f"Wrote {len(hr)} HR rows and {len(days)} day files to {folder} (generated, seed 54)")
    for p in planted:
        print("  planted:", p)
    return 0


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