"""Generate the public Billing Replay test shape independently with Faker + Python.

Pass the directory containing the public replay.py and Parquet files, then an
empty output directory. The reference provides table schemas and the verifier
only; no reference row data or answer labels are read by the generator.
"""

import argparse
import random
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

import duckdb
from faker import Faker

FAMILIES = ("pending_retry", "already_settled", "late_visibility",
            "out_of_order", "duplicate_capture")


def generate(reference, output):
    fake = Faker("en_US")
    fake.seed_instance(8025)
    rng = random.Random(8025)
    output.mkdir(parents=True, exist_ok=True)
    if any(output.iterdir()):
        raise ValueError("Choose an empty output directory.")
    db = duckdb.connect()
    for name in ("accounts", "invoices", "payments", "refunds",
                 "processor_events", "tasks", "answers", "pairs"):
        db.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet(?) LIMIT 0",
                   [str(reference / f"{name}.parquet")])

    def add(name, *row):
        db.execute(f"INSERT INTO {name} VALUES ({','.join('?' for _ in row)})", row)

    for n in range(40):
        family = FAMILIES[n % len(FAMILIES)]
        account, invoice, payment, refund, event = (
            f"{prefix}-{n:03d}" for prefix in ("acct", "inv", "pay", "rfd", "evt"))
        company, plan = fake.company(), rng.choice(("basic", "pro", "team"))
        total = rng.randint(1000, 100000)
        refund_amount = 4752 if n == 0 else rng.randint(1, total)
        total = max(total, refund_amount)
        issued = datetime(2026, 1, 1, tzinfo=timezone.utc) + timedelta(days=n)
        captured = issued + timedelta(minutes=10)
        requested = issued + timedelta(hours=1)
        happened = issued + timedelta(hours=2)
        cutoff = issued + timedelta(hours=8)
        cases = []
        for v in (0, 1):
            case = f"{n:03d}-{v}"
            cases.append(case)
            add("accounts", case, account, company, plan)
            add("invoices", case, invoice, account, total, "USD", issued)
            add("payments", case, payment, invoice, total, captured)
            add("refunds", case, refund, payment, refund_amount, requested)
            status = ({"pending_retry": "pending", "already_settled": "succeeded"}
                      .get(family, "failed") if v else "failed")
            task, subject, action, amount = "refund_attempt", refund, "retry_refund", refund_amount
            evidence = [refund, event]
            if family == "late_visibility" and v:
                action, amount, evidence = "manual_review", 0, [refund]
            else:
                add("processor_events", case, event, refund, status,
                    happened + timedelta(minutes=10), happened)
                if status != "failed":
                    action, amount = ("wait" if status == "pending" else "no_action"), 0
            if family == "out_of_order":
                other = event + "-pending"
                add("processor_events", case, other, refund, "pending",
                    happened + timedelta(minutes=20), happened + timedelta(minutes=1 if v else -1))
                if v:
                    action, amount, evidence = "wait", 0, [refund, other]
            if family == "duplicate_capture":
                other = payment + "-second"
                add("payments", case, other, invoice, total if v else total // 2,
                    captured + timedelta(seconds=1))
                task, subject = "duplicate_capture", invoice
                action, amount = ("refund_duplicate", total) if v else ("manual_review", 0)
                evidence = [invoice, payment, other]
            question = "What should happen as of the cutoff? Return the action, amount in cents, and evidence IDs."
            add("tasks", case, task, subject, question, cutoff)
            add("answers", case, action, amount, sorted(evidence))
        add("pairs", f"pair-{n:03d}", cases, family)

    for (name,) in db.execute("SHOW TABLES").fetchall():
        db.execute(f"COPY {name} TO (?) (FORMAT PARQUET, COMPRESSION ZSTD)",
                   [str(output / f"{name}.parquet")])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("reference", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    generate(args.reference, args.output)
    sys.path.insert(0, str(args.reference.resolve()))
    from replay import connect, verify
    answers, pairs = verify(connect(args.output))
    print(f"PASS: Faker + Python, {len(answers)} cases, {len(pairs)} one-record pairs")
