File size: 54,343 Bytes
92c67c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
"""Content generators for documents that are not IRS forms.

Each generator returns ``(items, sub_kind)`` for ``render.render``. Statement
kinds deliberately reuse tax-form vocabulary (a mortgage statement shows
interest paid year to date and says the Form 1098 is coming; a final paystub
shows year-to-date wages) because that overlap is exactly where the v1.0 head
failed. The label is what the document is, not which forms it mentions.
"""

from __future__ import annotations

import random

from render import address, date, ein, masked, money, person
from specs import (BANKS, BROKERS, BUSINESSES, CARD_ISSUERS, CARD_PRODUCTS, CHARITIES, CITIES, CLINICS, COUNTIES,
                   EMPLOYERS, EXCHANGES, HSA_TRUSTEES, INSURERS, LENDERS, MAKES, OTHER_TAX_FORMS, RETIREMENT_ADMINS,
                   SCHOOLS, SECURITIES, SERVICERS, STORES, TELCOS, UNKNOWN_KINDS, UTILITIES)

MERCHANTS = ["WHOLE FOODS #1021", "SHELL OIL 5741", "AMAZON MKTPLACE", "NETFLIX.COM", "TARGET T-2231", "UBER TRIP",
             "COSTCO WHSE #412", "CVS/PHARMACY 0832", "DELTA AIR LINES", "STARBUCKS #11872", "HOME DEPOT 0612"]


def _period(rng: random.Random, year: int) -> tuple[str, str]:
    m = rng.randint(1, 12)
    return f"{m:02d}/01/{year}", f"{m:02d}/{rng.choice([28, 30, 31]) if m != 2 else 28}/{year}"


def _txns(rng: random.Random, year: int, n: int, signed: bool = True) -> list[list[str]]:
    rows = []
    for _ in range(n):
        amount = rng.uniform(4, 900)
        sign = "-" if signed and rng.random() < 0.8 else ""
        rows.append([f"{rng.randint(1, 12):02d}/{rng.randint(1, 28):02d}", rng.choice(MERCHANTS), f"{sign}{amount:,.2f}"])
    return rows


def _mention(rng: random.Random, form: str, year: int, p: float = 0.45) -> list[tuple]:
    """Statements often announce a tax form; that does not make them the form."""
    if rng.random() > p:
        return []
    return [("line", rng.choice([
        f"Your {year} Form {form} will be available online by January 31, {year + 1}.",
        f"Tax reminder: amounts on this statement may differ from your Form {form}.",
        f"This statement is not a Form {form}. Keep it for your records.",
        f"IRS Form {form} information for {year} will be mailed separately.",
    ]))]


def bank_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    bank = rng.choice(BANKS)
    kind = rng.choice(["checking", "savings", "money_market", "year_end"])
    start, end = _period(rng, year)
    begin = rng.uniform(200, 60000)
    items: list[tuple] = [("line", bank), ("title", {"checking": "Checking Account Statement", "savings": "Savings Statement",
                                                     "money_market": "Money Market Account Statement",
                                                     "year_end": f"{year} Year-End Account Summary"}[kind])]
    items += [("kv", "Account number", masked(rng, 4)), ("kv", "Statement period", f"{start} - {end}"),
              ("line", person(rng)), ("line", " ".join(address(rng)))]
    deposits, withdrawals = rng.uniform(100, 9000), rng.uniform(50, 8000)
    items += [("line", "Account summary"), ("kv", "Beginning balance", f"${begin:,.2f}"),
              ("kv", "Deposits and other credits", f"${deposits:,.2f}"),
              ("kv", "Withdrawals and other debits", f"-${withdrawals:,.2f}"),
              ("kv", "Ending balance", f"${max(0.0, begin + deposits - withdrawals):,.2f}")]
    if kind != "checking" or rng.random() < 0.4:
        items += [("kv", "Interest paid this period", money(rng, 0.01, 60)),
                  ("kv", "Interest paid year-to-date", money(rng, 1, 900)),
                  ("kv", "Annual percentage yield earned", f"{rng.uniform(0.01, 4.8):.2f}%")]
    if kind != "year_end":
        items.append(("table", ["Date", "Description", "Amount"], _txns(rng, year, rng.randint(3, 7))))
    items += _mention(rng, "1099-INT", year)
    items.append(("line", rng.choice(["Member FDIC", "Federally insured by NCUA", "Equal Housing Lender"])))
    return items, kind


def credit_card_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["monthly", "monthly", "year_end_summary"])
    items: list[tuple] = [("line", rng.choice(CARD_ISSUERS)), ("title", rng.choice(CARD_PRODUCTS))]
    if kind == "year_end_summary":
        items.append(("title", f"{year} Year-End Summary"))
        cats = ["Dining", "Groceries", "Travel", "Gas", "Merchandise", "Services"]
        items.append(("table", ["Category", "Transactions", "Total"],
                      [[c, str(rng.randint(2, 90)), f"{rng.uniform(80, 9000):,.2f}"] for c in rng.sample(cats, 4)]))
        items.append(("kv", "Total purchases this year", money(rng, 4000, 60000)))
        items.append(("kv", "Total interest charged this year", money(rng, 0, 900)))
        items.append(("line", "This summary is provided for your records and is not a tax form."))
    else:
        prev = rng.uniform(0, 8000)
        items += [("kv", "Account ending in", masked(rng, 4)[-4:]),
                  ("kv", "Opening/Closing Date", " - ".join(_period(rng, year))),
                  ("line", "Account Summary"), ("kv", "Previous Balance", f"${prev:,.2f}"),
                  ("kv", "Payments, Credits", f"-${prev:,.2f}"), ("kv", "Purchases", money(rng, 50, 5000, 1)),
                  ("kv", "Fees Charged", "$0.00"), ("kv", "Interest Charged", money(rng, 0, 120, 1)),
                  ("kv", "New Balance", money(rng, 50, 6000, 1)), ("kv", "Minimum Payment Due", money(rng, 25, 200, 1)),
                  ("kv", "Payment Due Date", date(rng, year)),
                  ("kv", "Purchase APR", f"{rng.uniform(17, 29.9):.2f}%")]
        items.append(("table", ["Trans Date", "Description", "Amount"], _txns(rng, year, rng.randint(3, 7), signed=False)))
        if rng.random() < 0.5:
            items.append(("line", "Late Payment Warning: If we do not receive your minimum payment by the date listed above, you may have to pay a late fee."))
    return items, kind


def mortgage_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["monthly", "monthly", "monthly", "escrow_analysis", "payoff"])
    servicer = rng.choice(SERVICERS)
    principal = rng.uniform(90000, 640000)
    items: list[tuple] = [("line", servicer)]
    street, city = address(rng)
    if kind == "escrow_analysis":
        items += [("title", "Annual Escrow Account Disclosure Statement"), ("kv", "Loan number", masked(rng, 6)),
                  ("kv", "Property address", f"{street} {city}"),
                  ("kv", "Projected property taxes", money(rng, 1500, 14000)),
                  ("kv", "Projected homeowners insurance", money(rng, 700, 4200)),
                  ("kv", "Escrow shortage", money(rng, 0, 1200)),
                  ("kv", "New monthly escrow payment", money(rng, 150, 1500)),
                  ("kv", "New total monthly payment effective", date(rng, year + 1))]
    elif kind == "payoff":
        items += [("title", "Mortgage Payoff Statement"), ("kv", "Loan number", masked(rng, 6)),
                  ("kv", "Good through date", date(rng, year)), ("kv", "Unpaid principal balance", f"${principal:,.2f}"),
                  ("kv", "Interest from last paid date", money(rng, 200, 2200)), ("kv", "Recording fee", "$45.00"),
                  ("kv", "Total amount to pay off loan", f"${principal + rng.uniform(300, 2500):,.2f}")]
    else:
        interest = rng.uniform(250, 3200)
        items += [("title", rng.choice(["Mortgage Statement", "Monthly Mortgage Statement", "Home Loan Statement"])),
                  ("kv", "Statement date", date(rng, year)), ("kv", "Loan number", masked(rng, 6)),
                  ("kv", "Property address", f"{street} {city}"), ("kv", "Payment due date", date(rng, year)),
                  ("kv", "Amount due", money(rng, 900, 5200, 1)), ("line", "Explanation of amount due"),
                  ("kv", "Principal", money(rng, 200, 2500)), ("kv", "Interest", f"{interest:,.2f}"),
                  ("kv", "Escrow (for taxes and insurance)", money(rng, 150, 1500)),
                  ("kv", "Regular monthly payment", money(rng, 900, 5200)),
                  ("line", "Past payments breakdown  Paid last month  Paid year to date"),
                  ("kv", "Interest paid year to date", f"{interest * rng.randint(2, 12):,.2f}"),
                  ("kv", "Outstanding principal", f"${principal:,.2f}"),
                  ("kv", "Escrow balance", money(rng, 200, 6000, 1)),
                  ("kv", "Interest rate", f"{rng.uniform(2.5, 7.9):.3f}%")]
        if rng.random() < 0.5:
            items.append(("line", "If you are experiencing financial difficulty, call a HUD-approved housing counselor."))
        if rng.random() < 0.3:
            items.append(("line", "Late fee of $75.00 will be charged if payment is received after the 16th."))
    items += _mention(rng, "1098", year, 0.55)
    items.append(("line", "This is an attempt to collect a debt. NMLS ID " + str(rng.randint(1000, 999999))))
    return items, kind


def loan_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["auto", "student", "personal", "heloc"])
    lender = rng.choice(LENDERS)
    title = rng.choice({"auto": ["Auto Loan Statement", "Vehicle Loan Billing Statement", "Your auto loan bill"],
                        "student": ["Student Loan Statement", "Your monthly student loan bill", "Billing Statement - Student Loans"],
                        "personal": ["Personal Loan Statement", "Installment Loan Statement", "Your loan bill"],
                        "heloc": ["Home Equity Line of Credit Statement", "HELOC Billing Statement"]}[kind])
    balance = rng.uniform(0, 90000) if rng.random() > 0.1 else 0.0
    items: list[tuple] = [("line", lender), ("title", title), ("kv", "Account number", masked(rng, 6)),
                          ("kv", "Statement period", " - ".join(_period(rng, year))),
                          ("kv", rng.choice(["Principal balance", "Outstanding principal", "Current principal", "Unpaid principal balance", "Remaining balance"]), f"${balance:,.2f}"),
                          ("kv", rng.choice(["Interest rate", "APR", "Fixed rate"]), f"{rng.uniform(2.9, 13.9):.2f}%"),
                          ("kv", rng.choice(["Payment due", "Current amount due", "Amount due", "Monthly payment"]), money(rng, 80, 1400, 1)),
                          ("kv", rng.choice(["Due date", "Payment due date", "Due by"]), date(rng, year))]
    if kind == "auto":
        make, model = rng.choice(MAKES)
        items += [("kv", "Vehicle", f"{year - rng.randint(0, 5)} {make} {model}"),
                  ("kv", "Payments remaining", str(rng.randint(0, 60)))]
    if kind == "student":
        items += [("kv", "Loan type", rng.choice(["Direct Subsidized", "Direct Unsubsidized", "Private refinance"])),
                  ("kv", "Interest paid this year", money(rng, 50, 2500)),
                  ("kv", "Repayment plan", rng.choice(["Standard", "Income-Driven Repayment", "Graduated"]))]
        items += _mention(rng, "1098-E", year, 0.6)
    if kind == "heloc":
        items += [("kv", "Credit limit", money(rng, 20000, 150000)), ("kv", "Available credit", money(rng, 1000, 80000))]
        items += _mention(rng, "1098", year)
    if balance == 0.0:
        items.append(("line", "Loan status: Paid in full"))
    return items, kind


def brokerage_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["monthly", "quarterly", "holdings_export"])
    items: list[tuple] = [("line", rng.choice(BROKERS))]
    items.append(("title", {"monthly": "Investment Report", "quarterly": "Quarterly Account Statement",
                            "holdings_export": "Positions"}[kind]))
    items += [("kv", "Account", rng.choice(["Individual Brokerage Account", "Joint WROS", "Individual - TOD"]) + " " + masked(rng, 4)),
              ("kv", "Statement period", " - ".join(_period(rng, year)))]
    begin = rng.uniform(1000, 900000)
    if kind != "holdings_export":
        items += [("kv", "Beginning account value", f"${begin:,.2f}"),
                  ("kv", "Ending account value", f"${begin * rng.uniform(0.9, 1.12):,.2f}"),
                  ("line", "Income summary  This period  Year to date"),
                  ("kv", "Dividends", f"{rng.uniform(0, 900):,.2f}  {rng.uniform(100, 8000):,.2f}"),
                  ("kv", "Interest", f"{rng.uniform(0, 90):,.2f}  {rng.uniform(1, 600):,.2f}"),
                  ("kv", "Realized gain/loss", f"{rng.uniform(-3000, 9000):,.2f}")]
    rows = []
    for sym in rng.sample(SECURITIES[:6] + ["SCHB", "IVV", "QQQ"], 4):
        qty = rng.uniform(1, 400)
        price = rng.uniform(20, 500)
        rows.append([sym, f"{qty:,.3f}", f"{price:,.2f}", f"{qty * price:,.2f}", f"{rng.uniform(-2000, 9000):,.2f}"])
    items.append(("table", ["Symbol", "Quantity", "Last Price", "Current Value", "Total Gain/Loss"], rows))
    items += _mention(rng, "1099", year, 0.5)
    if rng.random() < 0.5:
        items.append(("line", "Securities offered through a member of FINRA/SIPC. Not FDIC insured."))
    return items, kind


def retirement_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["401k_quarterly", "ira_statement", "403b_annual"])
    admin = rng.choice(RETIREMENT_ADMINS)
    plan = f"{rng.choice(EMPLOYERS)} {'401(k) Savings Plan' if kind != '403b_annual' else '403(b) Plan'}"
    items: list[tuple] = [("line", admin)]
    if kind == "ira_statement":
        items += [("title", rng.choice(["Traditional IRA Statement", "Roth IRA Statement", "Rollover IRA Statement"])),
                  ("kv", "Account", masked(rng, 4)), ("kv", "Statement period", " - ".join(_period(rng, year))),
                  ("kv", f"{year} contributions", money(rng, 0, 7000)),
                  ("kv", f"{year - 1} contributions made in {year}", money(rng, 0, 7000)),
                  ("kv", "Account value", money(rng, 3000, 600000)),
                  ("kv", "Required minimum distribution for " + str(year), rng.choice(["Not applicable", money(rng, 1000, 30000)]))]
        items += _mention(rng, "5498", year, 0.5)
    else:
        items += [("title", "Retirement Account Statement" if kind == "401k_quarterly" else "Annual Benefit Statement"),
                  ("kv", "Plan", plan), ("kv", "Participant", person(rng)),
                  ("kv", "Statement period", " - ".join(_period(rng, year))),
                  ("kv", "Beginning balance", money(rng, 1000, 500000)),
                  ("kv", "Employee contributions (pre-tax)", money(rng, 300, 23000)),
                  ("kv", "Roth contributions", money(rng, 0, 5000)),
                  ("kv", "Employer match", money(rng, 100, 9000)),
                  ("kv", "Investment gain/loss", f"{rng.uniform(-20000, 60000):,.2f}"),
                  ("kv", "Ending balance", money(rng, 1000, 600000)),
                  ("kv", "Vested balance", money(rng, 1000, 600000)),
                  ("kv", "Personal rate of return", f"{rng.uniform(-8, 22):.1f}%")]
        funds = ["Target Retirement 2050 Fund", "S&P 500 Index Fund", "Stable Value Fund", "Total Bond Index"]
        items.append(("table", ["Investment", "Allocation", "Balance"],
                      [[f, f"{rng.randint(5, 80)}%", f"{rng.uniform(500, 200000):,.2f}"] for f in rng.sample(funds, 3)]))
        items += _mention(rng, "1099-R", year, 0.25)
    return items, kind


def hsa_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["monthly", "transaction_export", "annual_summary"])
    items: list[tuple] = [("line", rng.choice(HSA_TRUSTEES)),
                          ("title", {"monthly": "Health Savings Account Statement", "transaction_export": "HSA Transaction History",
                                     "annual_summary": f"{year} HSA Annual Summary"}[kind]),
                          ("kv", "Account holder", person(rng)), ("kv", "Account number", masked(rng, 4))]
    if kind != "transaction_export":
        items += [("kv", "Cash balance", money(rng, 100, 9000)), ("kv", "Invested balance", money(rng, 0, 40000)),
                  ("kv", "Employer contributions", money(rng, 0, 1500)), ("kv", "Employee contributions", money(rng, 100, 4300)),
                  ("kv", "Distributions / claims paid", money(rng, 0, 4000)), ("kv", "Interest and earnings", money(rng, 0, 900))]
    rows = []
    for _ in range(rng.randint(3, 6)):
        desc, sign = rng.choice([("Payroll contribution", ""), ("Employer contribution", ""),
                                 ("Card purchase CVS/PHARMACY", "-"), ("Claim reimbursement - Sample Family Clinic", "-"),
                                 ("Interest", ""), ("Card purchase Brightsmile Dental", "-")])
        rows.append([date(rng, year), desc, f"{sign}{rng.uniform(5, 800):,.2f}"])
    items.append(("table", ["Date", "Description", "Amount"], rows))
    items += _mention(rng, rng.choice(["5498-SA", "1099-SA"]), year, 0.4)
    return items, kind


def paystub(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["biweekly", "biweekly", "semimonthly", "final_of_year"])
    employer = rng.choice(EMPLOYERS)
    rate = rng.uniform(16, 95)
    hours = rng.choice([80, 86.67, 40, 75])
    gross = rate * hours
    periods = 26 if kind != "final_of_year" else 26
    ytd_mult = periods if kind == "final_of_year" else rng.randint(2, 24)
    items: list[tuple] = [("line", employer), ("line", " ".join(address(rng))),
                          ("title", rng.choice(["Earnings Statement", "Pay Statement", "Payroll Advice", "Statement of Earnings and Deductions"]))]
    start, end = _period(rng, year)
    items += [("kv", "Employee", person(rng)), ("kv", "Employee ID", str(rng.randint(10000, 99999))),
              ("kv", "Pay period", f"{start} - {end}"),
              ("kv", "Pay date", f"12/31/{year}" if kind == "final_of_year" else date(rng, year))]
    items.append(("table", ["Earnings", "Rate", "Hours", "Current", "YTD"],
                  [["Regular", f"{rate:.2f}", f"{hours:.2f}", f"{gross:,.2f}", f"{gross * ytd_mult:,.2f}"],
                   ["Overtime", f"{rate * 1.5:.2f}", f"{rng.randint(0, 9):.2f}", f"{rng.uniform(0, 600):,.2f}", f"{rng.uniform(0, 9000):,.2f}"]]))
    ded = [("Federal Income Tax", 0.11), ("Social Security", 0.062), ("Medicare", 0.0145), ("State Income Tax", 0.04),
           ("401(k)", 0.06), ("Medical Pre-Tax", 0.03)]
    items.append(("table", ["Deductions", "Current", "YTD"],
                  [[n, f"{gross * r:,.2f}", f"{gross * r * ytd_mult:,.2f}"] for n, r in ded if rng.random() < 0.9]))
    items += [("kv", "Gross pay", f"{gross:,.2f}"), ("kv", "Net pay", f"{gross * 0.68:,.2f}"),
              ("kv", "Direct deposit to checking", masked(rng, 4))]
    if kind == "final_of_year" and rng.random() < 0.6:
        items.append(("line", f"Your {year} Form W-2 will be available in the employee portal by January 31."))
    return items, kind


def insurance_document(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["auto_declarations", "home_declarations", "eob", "life_annual", "premium_notice"])
    insurer = rng.choice(INSURERS)
    items: list[tuple] = [("line", insurer)]
    if kind == "auto_declarations":
        make, model = rng.choice(MAKES)
        items += [("title", "Auto Policy Declarations"), ("kv", "Policy number", f"PA-{rng.randint(100000, 999999)}"),
                  ("kv", "Policy period", f"{date(rng, year)} to {date(rng, year + 1)}"),
                  ("kv", "Named insured", person(rng)), ("kv", "Vehicle", f"{year - rng.randint(0, 9)} {make} {model}"),
                  ("kv", "Bodily injury liability", "$100,000 / $300,000"), ("kv", "Collision deductible", "$500"),
                  ("kv", "Six-month premium", money(rng, 300, 1900, 1))]
    elif kind == "home_declarations":
        items += [("title", "Homeowners Policy Declarations"), ("kv", "Policy number", f"HO-{rng.randint(100000, 999999)}"),
                  ("kv", "Residence premises", " ".join(address(rng))), ("kv", "Coverage A - Dwelling", money(rng, 150000, 900000, 1)),
                  ("kv", "Coverage E - Personal liability", "$300,000"), ("kv", "All other perils deductible", "$1,000"),
                  ("kv", "Annual premium", money(rng, 700, 5200, 1)), ("kv", "Mortgagee", rng.choice(SERVICERS))]
    elif kind == "eob":
        items += [("title", "Explanation of Benefits"), ("line", "THIS IS NOT A BILL"), ("kv", "Member", person(rng)),
                  ("kv", "Claim number", str(rng.randint(10 ** 9, 10 ** 10))), ("kv", "Provider", rng.choice(CLINICS)),
                  ("kv", "Date of service", date(rng, year))]
        billed = rng.uniform(90, 4000)
        items.append(("table", ["Amount billed", "Plan discount", "Plan paid", "You may owe"],
                      [[f"{billed:,.2f}", f"{billed * 0.3:,.2f}", f"{billed * 0.5:,.2f}", f"{billed * 0.2:,.2f}"]]))
        items.append(("kv", "Deductible met year to date", money(rng, 0, 3000, 1)))
    elif kind == "life_annual":
        items += [("title", "Annual Policy Statement - Universal Life"), ("kv", "Policy number", f"UL{rng.randint(10 ** 6, 10 ** 7)}"),
                  ("kv", "Insured", person(rng)), ("kv", "Death benefit", money(rng, 50000, 1000000, 1)),
                  ("kv", "Premiums paid this year", money(rng, 300, 9000, 1)), ("kv", "Cash value", money(rng, 0, 90000, 1)),
                  ("kv", "Cost of insurance charges", money(rng, 100, 3000, 1))]
    else:
        items += [("title", "Premium Due Notice"), ("kv", "Policy number", f"{rng.randint(10 ** 7, 10 ** 8)}"),
                  ("kv", "Policyholder", person(rng)), ("kv", "Amount due", money(rng, 80, 2400, 1)),
                  ("kv", "Due date", date(rng, year)), ("line", "Pay online to avoid a lapse in coverage.")]
    if rng.random() < 0.3:
        items.append(("line", "Health coverage information forms (1095) are issued separately when required."))
    return items, kind


def crypto_tax_report(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["gain_loss", "transaction_history", "tax_software_summary"])
    source = rng.choice(EXCHANGES + ["CoinLedger-style report", "TaxBit-style report"])
    items: list[tuple] = [("line", source),
                          ("title", {"gain_loss": f"{year} Realized Gains and Losses Report",
                                     "transaction_history": "Crypto Transaction History Export",
                                     "tax_software_summary": f"{year} Crypto Tax Summary"}[kind])]
    items += [("kv", "Account", person(rng)), ("kv", "Cost basis method", rng.choice(["FIFO", "HIFO", "Specific ID"]))]
    if kind != "transaction_history":
        items += [("kv", "Short-term realized gain/loss", f"{rng.uniform(-9000, 20000):,.2f}"),
                  ("kv", "Long-term realized gain/loss", f"{rng.uniform(-9000, 40000):,.2f}"),
                  ("kv", "Staking and other income", money(rng, 0, 3000))]
    rows = []
    for _ in range(rng.randint(3, 6)):
        coin = rng.choice(["BTC", "ETH", "SOL", "USDC", "ADA"])
        proceeds = rng.uniform(20, 20000)
        rows.append([coin, f"{rng.uniform(0.001, 30):.6f}", date(rng, year - rng.randint(0, 2)), date(rng, year),
                     f"{proceeds:,.2f}", f"{proceeds * rng.uniform(0.5, 1.4):,.2f}"])
    items.append(("table", ["Asset", "Amount", "Date Acquired", "Date Sold", "Proceeds", "Cost Basis"], rows))
    items.append(("line", rng.choice([
        "This report is for informational purposes and is not an IRS form.",
        "Use this report to prepare Form 8949; it is not a Form 1099-DA.",
        "Generated by tax software from your exchange history.",
    ])))
    return items, kind


def property_tax_bill(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["annual_bill", "installment_notice", "paid_receipt"])
    items: list[tuple] = [("line", rng.choice(COUNTIES)),
                          ("title", {"annual_bill": f"{year} Real Estate Property Tax Bill",
                                     "installment_notice": "Second Installment Property Tax Notice",
                                     "paid_receipt": "Property Tax Payment Receipt"}[kind]),
                          ("kv", "Parcel number", f"{rng.randint(10, 99)}-{rng.randint(10, 99)}-{rng.randint(100, 999)}-{rng.randint(10, 99)}"),
                          ("kv", "Property location", " ".join(address(rng))), ("kv", "Owner", person(rng)),
                          ("kv", "Assessed value", money(rng, 60000, 700000, 1)),
                          ("kv", "Homestead exemption", money(rng, 0, 10000, 1)),
                          ("kv", "Tax rate", f"{rng.uniform(1.1, 9.8):.4f}%")]
    items.append(("table", ["Taxing district", "Amount"],
                  [[d, f"{rng.uniform(100, 5000):,.2f}"] for d in rng.sample(
                      ["County General", "School District 204", "City of Testville", "Park District", "Library District",
                       "Community College 502"], 4)]))
    total = rng.uniform(1200, 16000)
    items += [("kv", "Total tax", f"${total:,.2f}"), ("kv", "First installment due", date(rng, year)),
              ("kv", "Second installment due", date(rng, year))]
    if kind == "paid_receipt":
        items.append(("kv", "Amount paid", f"${total / 2:,.2f}"))
    if rng.random() < 0.4:
        items.append(("line", "If your taxes are paid through an escrow account, forward this bill to your mortgage company."))
    return items, kind


def profit_and_loss(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["annual", "monthly", "cash_basis"])
    business = rng.choice(BUSINESSES)
    items: list[tuple] = [("line", business), ("title", rng.choice(["Profit and Loss", "Profit & Loss Statement", "Income Statement"])),
                          ("line", f"January - December {year}" if kind != "monthly" else f"{rng.choice(['March', 'June', 'October'])} {year}"),
                          ("line", "Cash Basis" if kind == "cash_basis" else "Accrual Basis")]
    sales = rng.uniform(20000, 600000)
    cogs = sales * rng.uniform(0.1, 0.5)
    exp = [("Advertising & Marketing", 0.03), ("Contract Labor", 0.08), ("Insurance", 0.02), ("Office Supplies", 0.01),
           ("Rent or Lease", 0.06), ("Software Subscriptions", 0.01), ("Travel", 0.02), ("Utilities", 0.01)]
    rows = [[n, f"{sales * r * rng.uniform(0.5, 1.5):,.2f}"] for n, r in exp if rng.random() < 0.8]
    total_exp = sum(float(r[1].replace(",", "")) for r in rows)
    items += [("line", "Income"), ("kv", "Sales", f"{sales:,.2f}"), ("kv", "Total Income", f"{sales:,.2f}"),
              ("kv", "Cost of Goods Sold", f"{cogs:,.2f}"), ("kv", "Gross Profit", f"{sales - cogs:,.2f}"),
              ("table", ["Expenses", "Total"], rows), ("kv", "Total Expenses", f"{total_exp:,.2f}"),
              ("kv", "Net Operating Income", f"{sales - cogs - total_exp:,.2f}"),
              ("kv", "Net Income", f"{sales - cogs - total_exp:,.2f}")]
    return items, kind


def consolidated_1099(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["summary_page", "div_int_detail", "b_detail"])
    broker = rng.choice(BROKERS)
    items: list[tuple] = [("line", broker), ("title", rng.choice([f"{year} Consolidated Form 1099", "Tax Reporting Statement",
                                                                  f"{year} Tax Information Statement",
                                                                  "Form 1099 Composite & Year-End Summary"])),
                          ("kv", "Account", masked(rng, 4)), ("kv", "Recipient", person(rng)),
                          ("kv", "Payer's Federal ID number", ein(rng)), ("line", "Copy B for Recipient  OMB No. 1545-0715"),
                          ("line", f"Page {rng.randint(1, 3)} of {rng.randint(8, 30)}")]
    if kind in ("summary_page", "div_int_detail"):
        items += [("line", "1099-DIV  Dividends and Distributions"), ("kv", "1a Total ordinary dividends", money(rng, 10, 9000, 0)),
                  ("kv", "1b Qualified dividends", money(rng, 10, 8000, 0)), ("kv", "2a Total capital gain distributions", money(rng, 0, 3000, 0)),
                  ("line", "1099-INT  Interest Income"), ("kv", "1 Interest income", money(rng, 0, 900, 0)),
                  ("line", "1099-MISC  Miscellaneous Information"), ("kv", "3 Other income", money(rng, 0, 200, 0))]
    if kind in ("summary_page", "b_detail"):
        items += [("line", "1099-B  Summary of Proceeds, Gains & Losses, Adjustments and Withholding"),
                  ("table", ["Term", "Form 8949 type", "Proceeds", "Cost basis", "Wash sale loss disallowed", "Net gain or loss"],
                   [["Short", "A (basis reported to the IRS)", f"{rng.uniform(100, 90000):,.2f}", f"{rng.uniform(100, 90000):,.2f}", "0.00", f"{rng.uniform(-5000, 9000):,.2f}"],
                    ["Long", "D (basis reported to the IRS)", f"{rng.uniform(100, 90000):,.2f}", f"{rng.uniform(100, 90000):,.2f}", "0.00", f"{rng.uniform(-5000, 30000):,.2f}"]])]
    items.append(("line", "This is important tax information and is being furnished to the Internal Revenue Service."))
    return items, kind


def estimated_tax_confirmation(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["direct_pay", "eftps", "state_portal", "card_processor"])
    title = {"direct_pay": "IRS Direct Pay - Payment Confirmation", "eftps": "EFTPS Payment Acknowledgement",
             "state_portal": "Estimated Payment Submitted", "card_processor": "Tax Payment Receipt"}[kind]
    items: list[tuple] = [("title", title), ("kv", "Confirmation number", "-".join(str(rng.randint(1000, 9999)) for _ in range(3))),
                          ("kv", "Name", person(rng)), ("kv", "Reason for payment", "Estimated Tax"),
                          ("kv", "Apply payment to", rng.choice(["1040ES (for 1040, 1040A, 1040EZ)", "Form 1040-ES", "Estimated tax"])),
                          ("kv", "Tax period for payment", str(year)), ("kv", "Payment amount", money(rng, 100, 20000, 1)),
                          ("kv", "Payment date", date(rng, year)), ("kv", "Bank account", masked(rng, 4))]
    if kind == "card_processor":
        items.append(("kv", "Convenience fee", money(rng, 2, 90, 1)))
    items.append(("line", rng.choice(["Keep this confirmation for your records.", "Your payment has been scheduled.",
                                      "Do not mail a voucher for payments made online."])))
    return items, kind


def tax_instructions(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    form = rng.choice(["1099-INT", "W-2", "1098", "1040", "1099-B", "1099-R", "Schedule C", "8949"])
    kind = rng.choice(["irs_instructions", "employer_guide", "preparer_checklist"])
    items: list[tuple] = []
    if kind == "irs_instructions":
        items += [("title", f"Instructions for Form {form}"), ("line", f"(Rev. January {year})"),
                  ("line", "Section references are to the Internal Revenue Code unless otherwise noted."),
                  ("line", "What's New"), ("line", f"Future developments. For the latest information about developments related to Form {form}, go to IRS.gov."),
                  ("line", "General Instructions"), ("line", "Specific Instructions"),
                  ("line", f"Box 1. Enter the amount reported to you. Do not include amounts reported on another form."),
                  ("line", "Paperwork Reduction Act Notice. We ask for the information on this form to carry out the Internal Revenue laws.")]
    elif kind == "employer_guide":
        items += [("title", f"Understanding your Form {form}"), ("line", f"This guide explains each box on the Form {form} you receive."),
                  ("line", "Box 1 shows the amount reported to the IRS."), ("line", "Boxes 15 through 17 show state information."),
                  ("line", "This page is an explanation only; your actual form is attached separately.")]
    else:
        items += [("title", f"{year} Tax Organizer Checklist"), ("line", "Please bring the following documents:"),
                  ("line", "☐ All Forms W-2 and 1099"), ("line", "☐ Form 1098 mortgage interest statements"),
                  ("line", "☐ Property tax bills and charitable receipts"), ("line", "☐ Last year's federal and state returns")]
    return items, kind


def annual_giving_statement(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["church", "nonprofit", "daf_grant_summary"])
    org = rng.choice(CHARITIES)
    items: list[tuple] = [("line", org), ("line", f"Tax ID {ein(rng)}  A 501(c)(3) organization"),
                          ("title", rng.choice([f"{year} Annual Giving Statement", f"Contribution Statement for {year}",
                                                "Year-End Giving Summary"])),
                          ("line", f"Dear {person(rng)},"), ("line", "Thank you for your generous support this year.")]
    gifts = [[date(rng, year), rng.choice(["Cash", "Check #" + str(rng.randint(1000, 9999)), "Online gift", "Stock transfer"]),
              f"{rng.uniform(10, 2500):,.2f}"] for _ in range(rng.randint(3, 8))]
    items.append(("table", ["Date", "Method", "Amount"], gifts))
    items.append(("kv", "Total contributions", f"${sum(float(g[2].replace(',', '')) for g in gifts):,.2f}"))
    items.append(("line", rng.choice(["No goods or services were provided in exchange for these contributions.",
                                      "Only intangible religious benefits were provided in exchange for your gifts."])))
    return items, kind


def donation_appeal(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    org = rng.choice(CHARITIES)
    kind = rng.choice(["year_end_letter", "email", "matching_campaign", "reply_card"])
    goal = rng.randint(20, 900) * 1000
    pool = [
        "Every gift provides warm meals and shelter for families in need.",
        f"Give ${rng.choice([25, 35, 50, 75])}, ${rng.choice([100, 150])}, or ${rng.choice([250, 500, 1000])} today.",
        f"A generous donor will match every gift until {date(rng, year)}.",
        "Donate now at our website or return the enclosed reply card.",
        "Your gift may be tax-deductible to the extent allowed by law.",
        f"We are ${goal:,} away from our {year} goal.",
        f"Last year you helped serve {rng.randint(400, 40000):,} neighbors.",
        "Become a monthly sustainer and make a difference all year long.",
        "P.S. Gifts made by December 31 count toward this year's campaign.",
        f"Scan the QR code or call {rng.randint(200, 989)}-555-{rng.randint(1000, 9999)} to give by phone.",
        "This is a solicitation for a charitable contribution, not a receipt.",
    ]
    items: list[tuple] = [("line", org), ("title", rng.choice(["Will you help a neighbor this winter?", "Your gift matters",
                                                               "Double your impact today", f"{year} Annual Appeal",
                                                               "Spring Giving Campaign", "Please give before midnight"])),
                          ("line", f"Dear {rng.choice([person(rng).split()[0], 'Friend', 'Neighbor', 'Supporter'])},")]
    items += [("line", s) for s in rng.sample(pool, rng.randint(3, 6))]
    if kind == "reply_card":
        items += [("kv", "Name", person(rng)), ("kv", "Gift amount", "$______"), ("line", "☐ Check enclosed  ☐ Charge my card")]
    return items, kind


def charity_event_receipt(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    org = rng.choice(CHARITIES)
    ticket = rng.uniform(75, 500)
    fmv = ticket * rng.uniform(0.2, 0.6)
    items: list[tuple] = [("line", org), ("title", rng.choice(["Gala Ticket Receipt", "Event Registration Receipt", "Charity Auction Receipt"])),
                          ("kv", "Attendee", person(rng)), ("kv", "Event date", date(rng, year)),
                          ("kv", "Amount paid", f"${ticket:,.2f}"), ("kv", "Fair market value of dinner and entertainment", f"${fmv:,.2f}"),
                          ("kv", "Deductible portion", f"${ticket - fmv:,.2f}"),
                          ("line", "The deductible amount is limited to the excess of your payment over the value of goods and services received.")]
    return items, "event"


def medical_receipt(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    kind = rng.choice(["clinic", "pharmacy", "dental", "hospital_statement"])
    items: list[tuple] = [("line", rng.choice(CLINICS)),
                          ("title", {"clinic": "Patient Receipt", "pharmacy": "Prescription Receipt", "dental": "Dental Visit Receipt",
                                     "hospital_statement": "Patient Account Statement"}[kind]),
                          ("kv", "Patient", person(rng)), ("kv", "Date of service", date(rng, year))]
    charge = rng.uniform(20, 3000)
    if kind == "pharmacy":
        items += [("kv", "Rx #", str(rng.randint(100000, 999999))), ("kv", "Drug", rng.choice(["Atorvastatin 20mg", "Amoxicillin 500mg", "Lisinopril 10mg"])),
                  ("kv", "Qty", str(rng.choice([30, 60, 90]))), ("kv", "Insurance paid", f"{charge * 0.7:,.2f}"),
                  ("kv", "Your copay", f"{charge * 0.3:,.2f}")]
    else:
        items.append(("table", ["CPT", "Description", "Charge"],
                      [[str(rng.choice([99213, 99214, 80053, 36415, 1110, 2391])), rng.choice(["Office visit", "Lab panel", "Cleaning", "Filling"]),
                        f"{charge:,.2f}"]]))
        items += [("kv", "Insurance adjustment", f"-{charge * 0.4:,.2f}"), ("kv", "Insurance paid", f"-{charge * 0.4:,.2f}"),
                  ("kv", "Patient paid", f"{charge * 0.2:,.2f}"), ("kv", "Balance due", "$0.00")]
    items.append(("kv", "Payment method", rng.choice(["Visa ****" + masked(rng, 4)[-4:], "HSA card", "Cash"])))
    return items, kind


def purchase_receipt(rng: random.Random, year: int) -> tuple[list[tuple], str]:
    store = rng.choice(STORES)
    lines = [[rng.choice(["USB-C Cable", "Printer Paper 10pk", "Drill Bit Set", "Organic Apples", "Monitor 27in", "LED Bulbs 4pk"]),
              str(rng.randint(1, 3)), f"{rng.uniform(2, 400):,.2f}"] for _ in range(rng.randint(2, 6))]
    sub = sum(float(r[2].replace(",", "")) for r in lines)
    items: list[tuple] = [("title", store), ("line", " ".join(address(rng))), ("line", f"{date(rng, year)} 3:41 PM  Store 0{rng.randint(10, 99)}"),
                          ("table", ["Item", "Qty", "Price"], lines), ("kv", "Subtotal", f"{sub:,.2f}"),
                          ("kv", "Sales tax", f"{sub * 0.07:,.2f}"), ("kv", "Total", f"{sub * 1.07:,.2f}"),
                          ("kv", "Visa", masked(rng, 4)), ("line", "Thank you for shopping! Returns within 30 days with receipt.")]
    return items, "retail"


def _fill(rng: random.Random, text: str, year: int) -> str:
    city, _ = rng.choice(CITIES)
    make, model = rng.choice(MAKES)
    values = {"utility": rng.choice(UTILITIES), "telco": rng.choice(TELCOS), "address": " ".join(address(rng)),
              "period": " - ".join(_period(rng, year)), "money": money(rng, 40, 3000, 1), "small": money(rng, 5, 300, 1),
              "date": date(rng, year), "acct": str(rng.randint(10 ** 7, 10 ** 9)), "name": person(rng),
              "company": rng.choice(["Oak Hollow Property Mgmt", "Riverbend Commons", "Granite Ridge"]),
              "plate": "".join(rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ0123456789") for _ in range(6)),
              "vin": "".join(rng.choice("ABCDEFGHJKLMNPRSTUVWXYZ0123456789") for _ in range(17)), "year": str(year - 3),
              "make": make, "model": model, "county": f"{city} County", "school": rng.choice(SCHOOLS),
              "employer": rng.choice(EMPLOYERS), "bank": rng.choice(BANKS), "insurer": rng.choice(INSURERS),
              "clinic": rng.choice(CLINICS).split()[0], "city_upper": city.upper(),
              "email": f"{rng.choice(['jo', 'avery', 'm.lee', 'casey88', 'priya.k'])}@example.com",
              "phone": f"{rng.randint(200, 989)}-555-{rng.randint(1000, 9999)}", "count": str(rng.randint(1, 600))}
    return text.format(**values)


def unknown_document(rng: random.Random, year: int, kind_index: int) -> tuple[list[tuple], str]:
    kind, titles, body = UNKNOWN_KINDS[kind_index]
    items: list[tuple] = [("title", _fill(rng, t, year)) for t in titles]
    items += [("line", _fill(rng, b, year)) for b in body if rng.random() < 0.9]
    return items, kind


def other_tax_form(rng: random.Random, year: int, form_index: int) -> tuple[list[tuple], str]:
    form, title, lines = OTHER_TAX_FORMS[form_index]
    items: list[tuple] = [("title", f"Form {form}"), ("title", title)]
    if rng.random() < 0.7:
        items.append(("line", str(year)))
    items.append(("line", rng.choice(["Department of the Treasury - Internal Revenue Service", "Copy B For Recipient",
                                      "Keep for your records", "Department of Revenue"])))
    items.append(("kv", rng.choice(["Name", "Recipient's name", "Taxpayer name"]), person(rng)))
    items.append(("kv", rng.choice(["Identification number", "Recipient's TIN", "SSN"]), masked(rng)))
    for line in lines:
        items.append(("kv", line, money(rng, 0, 30000, 0.3) if rng.random() < 0.8 else date(rng, year)))
    return items, form


GENERATORS = {
    "BANK_STATEMENT": bank_statement, "CREDIT_CARD_STATEMENT": credit_card_statement,
    "MORTGAGE_STATEMENT": mortgage_statement, "LOAN_STATEMENT": loan_statement,
    "BROKERAGE_STATEMENT": brokerage_statement, "RETIREMENT_ACCOUNT_STATEMENT": retirement_statement,
    "HSA_ACCOUNT_STATEMENT": hsa_statement, "PAYSTUB": paystub, "INSURANCE_DOCUMENT": insurance_document,
    "CRYPTO_TAX_REPORT": crypto_tax_report, "PROPERTY_TAX_BILL": property_tax_bill,
    "PROFIT_AND_LOSS_STATEMENT": profit_and_loss, "CONSOLIDATED_1099": consolidated_1099,
    "ESTIMATED_TAX_PAYMENT_CONFIRMATION": estimated_tax_confirmation, "TAX_INSTRUCTIONS": tax_instructions,
    "ANNUAL_GIVING_STATEMENT": annual_giving_statement, "DONATION_APPEAL": donation_appeal,
    "CHARITY_EVENT_RECEIPT": charity_event_receipt, "MEDICAL_RECEIPT": medical_receipt,
    "PURCHASE_RECEIPT": purchase_receipt,
}


# ── Raw exports: a header row and data rows, no document title ──────────────
# Account downloads (CSV/XLSX) are a common upload. Their only cues are the
# column names and row descriptions, so every statement label gets them, and
# UNKNOWN_DOCUMENT gets unrelated tables so "is a table" decides nothing.

def _amt(rng: random.Random, low: float, high: float, neg: float = 0.0) -> str:
    v = rng.uniform(low, high)
    return f"-{v:.2f}" if rng.random() < neg else f"{v:.2f}"


def _iso(rng: random.Random, year: int) -> str:
    return rng.choice([f"{year}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}",
                       f"{rng.randint(1, 12):02d}/{rng.randint(1, 28):02d}/{year}",
                       f"{rng.randint(1, 28):02d}/{rng.randint(1, 12):02d}/{year}"])


EXPORTS = {
    "BANK_STATEMENT": [
        (["Date", "Description", "Amount", "Running Bal."],
         lambda r, y: [_iso(r, y), r.choice(MERCHANTS + ["PAYROLL DIRECT DEP", "ONLINE TRANSFER TO SAV", "ATM WITHDRAWAL", "ZELLE FROM J SMITH"]), _amt(r, 3, 2500, 0.7), _amt(r, 100, 30000)]),
        (["Posting Date", "Description", "Amount", "Type", "Balance", "Check or Slip #"],
         lambda r, y: [_iso(r, y), r.choice(MERCHANTS + ["ACH DEPOSIT EMPLOYER", "CHECK 1043"]), _amt(r, 3, 2500, 0.7), r.choice(["DEBIT_CARD", "ACH_CREDIT", "CHECK_PAID", "ATM"]), _amt(r, 100, 30000), r.choice(["", "", "1043"])]),
        (["Transaction Date", "Transaction Description", "Debit", "Credit", "Balance"],
         lambda r, y: [_iso(r, y), r.choice(MERCHANTS + ["INTEREST PAYMENT", "MOBILE DEPOSIT"]), r.choice(["", _amt(r, 3, 900)]), r.choice(["", _amt(r, 1, 3000)]), _amt(r, 100, 30000)]),
        (["Date", "Payee", "Memo", "Withdrawal", "Deposit", "Balance"],
         lambda r, y: [_iso(r, y), r.choice(MERCHANTS), r.choice(["", "groceries", "rent", "utilities"]), _amt(r, 3, 900), "", _amt(r, 100, 30000)]),
    ],
    "CREDIT_CARD_STATEMENT": [
        (["Transaction Date", "Post Date", "Description", "Category", "Type", "Amount", "Memo"],
         lambda r, y: [_iso(r, y), _iso(r, y), r.choice(MERCHANTS), r.choice(["Groceries", "Travel", "Food & Drink", "Shopping", "Gas"]), r.choice(["Sale", "Sale", "Return", "Payment"]), _amt(r, 3, 900, 0.8), ""]),
        (["Date", "Description", "Card Member", "Account #", "Amount"],
         lambda r, y: [_iso(r, y), r.choice(MERCHANTS), person(r).upper(), "-" + str(r.randint(10000, 99999)), _amt(r, 3, 900)]),
        (["Trans. Date", "Post Date", "Description", "Amount", "Category"],
         lambda r, y: [_iso(r, y), _iso(r, y), r.choice(MERCHANTS + ["AUTOPAY PAYMENT - THANK YOU", "INTEREST CHARGE ON PURCHASES"]), _amt(r, 3, 900, 0.1), r.choice(["Merchandise", "Restaurants", "Payments and Credits"])]),
    ],
    "MORTGAGE_STATEMENT": [
        (["Payment Date", "Total Payment", "Principal", "Interest", "Escrow", "Principal Balance"],
         lambda r, y: [_iso(r, y), _amt(r, 900, 4500), _amt(r, 200, 1600), _amt(r, 300, 2500), _amt(r, 150, 1200), _amt(r, 60000, 640000)]),
        (["Date", "Transaction", "Amount", "Principal", "Interest", "Escrow", "Fees", "Unpaid Principal"],
         lambda r, y: [_iso(r, y), r.choice(["Regular monthly payment", "Escrow disbursement - county tax", "Hazard insurance disbursement", "Additional principal"]), _amt(r, 100, 4500), _amt(r, 0, 1600), _amt(r, 0, 2500), _amt(r, 0, 1200), "0.00", _amt(r, 60000, 640000)]),
        (["Due Date", "Amount Paid", "Principal Applied", "Interest Applied", "Escrow Deposit", "Remaining Balance"],
         lambda r, y: [_iso(r, y), _amt(r, 900, 4500), _amt(r, 200, 1600), _amt(r, 300, 2500), _amt(r, 150, 1200), _amt(r, 60000, 640000)]),
    ],
    "LOAN_STATEMENT": [
        (["Date", "Description", "Payment", "Principal", "Interest", "Balance"],
         lambda r, y: [_iso(r, y), r.choice(["Auto loan payment", "Student loan payment", "Loan payment", "Autopay", "Personal loan installment"]), _amt(r, 80, 1400), _amt(r, 40, 1200), _amt(r, 5, 400), _amt(r, 0, 90000)]),
        (["Posted", "Type", "Amount", "To Principal", "To Interest", "Outstanding Balance"],
         lambda r, y: [_iso(r, y), r.choice(["PAYMENT", "INTEREST ACCRUAL", "LATE FEE", "DISBURSEMENT", "INTEREST CAPITALIZATION"]), _amt(r, 5, 1400), _amt(r, 0, 1200), _amt(r, 0, 400), _amt(r, 0, 90000)]),
        (["Payment Date", "Amount Paid", "Principal Paid", "Interest Paid", "Late Fee", "Loan Balance"],
         lambda r, y: [_iso(r, y), _amt(r, 80, 1400), _amt(r, 40, 1200), _amt(r, 5, 400), "0.00", _amt(r, 0, 90000)]),
    ],
    "BROKERAGE_STATEMENT": [
        (["Symbol", "Description", "Quantity", "Price", "Market Value", "Cost Basis", "Gain/Loss"],
         lambda r, y: [r.choice(["VTI", "AAPL", "MSFT", "BND", "SCHD", "QQQ", "SPAXX**"]), r.choice(["VANGUARD TOTAL STOCK MKT ETF", "APPLE INC", "MONEY MARKET", "ISHARES CORE S&P 500"]), _amt(r, 1, 400), _amt(r, 1, 500), _amt(r, 100, 90000), _amt(r, 100, 80000), _amt(r, 1, 9000, 0.3)]),
        (["Account Number", "Account Name", "Symbol", "Description", "Quantity", "Last Price", "Current Value", "Total Gain/Loss Dollar", "Percent Of Account"],
         lambda r, y: ["Z" + str(r.randint(10 ** 7, 10 ** 8)), "Individual", r.choice(["FXAIX", "VOO", "NVDA", "AMZN"]), r.choice(["FIDELITY 500 INDEX", "VANGUARD S&P 500 ETF", "NVIDIA CORP"]), _amt(r, 1, 400), _amt(r, 1, 900), _amt(r, 100, 90000), _amt(r, 1, 9000, 0.3), f"{r.uniform(1, 60):.2f}%"]),
        (["Run Date", "Action", "Symbol", "Security Description", "Quantity", "Price", "Amount", "Settlement Date"],
         lambda r, y: [_iso(r, y), r.choice(["YOU BOUGHT", "YOU SOLD", "DIVIDEND RECEIVED", "REINVESTMENT", "INTEREST EARNED"]), r.choice(["VTI", "AAPL", "SCHD"]), r.choice(["VANGUARD INDEX FDS", "APPLE INC", "SCHWAB US DIVIDEND EQUITY ETF"]), _amt(r, 0, 100), _amt(r, 1, 500), _amt(r, 1, 9000, 0.5), _iso(r, y)]),
        (["Trade Date", "Transaction Type", "Investment Name", "Shares", "Share Price", "Net Amount"],
         lambda r, y: [_iso(r, y), r.choice(["Buy", "Sell", "Dividend", "Reinvestment", "Capital gain (LT)"]), r.choice(["Total Stock Market Index Admiral", "Total Bond Market ETF", "500 Index Admiral"]), _amt(r, 0, 100), _amt(r, 1, 500), _amt(r, 1, 9000, 0.5)]),
    ],
    "RETIREMENT_ACCOUNT_STATEMENT": [
        (["Date", "Fund", "Employee Contribution", "Employer Match", "Gain/Loss", "Balance"],
         lambda r, y: [_iso(r, y), r.choice(["Target Date 2055", "TDF2050", "S&P 500 Index", "Stable Value"]), _amt(r, 50, 1500), _amt(r, 0, 800), _amt(r, 1, 3000, 0.4), _amt(r, 1000, 600000)]),
        (["Pay Date", "Source", "Investment", "Amount", "Units", "Unit Price"],
         lambda r, y: [_iso(r, y), r.choice(["Employee Pre-Tax", "Roth 401(k)", "Safe Harbor Match", "Profit Sharing", "Rollover"]), r.choice(["Target Retirement 2050", "Stable Value Fund", "Large Cap Index"]), _amt(r, 20, 1500), _amt(r, 0, 60), _amt(r, 9, 300)]),
        (["Account", "Account Type", "Symbol", "Quantity", "Value", "Contributions YTD"],
         lambda r, y: ["..." + str(r.randint(1000, 9999)), r.choice(["Traditional IRA", "Roth IRA", "SEP IRA", "Rollover IRA", "SIMPLE IRA"]), r.choice(["VTI", "FXAIX", "VTTSX", "BND"]), _amt(r, 1, 400), _amt(r, 100, 300000), _amt(r, 0, 7000)]),
    ],
    "HSA_ACCOUNT_STATEMENT": [
        (["Date", "Description", "Type", "Amount", "Cash Balance"],
         lambda r, y: [_iso(r, y), r.choice(["Payroll contribution", "Employer HSA contribution", "Card purchase - Pharmacy", "Reimbursement to self", "HSA interest", "Transfer to HSA investments"]), r.choice(["Contribution", "Distribution", "Interest", "Transfer"]), _amt(r, 1, 900, 0.4), _amt(r, 50, 12000)]),
        (["Transaction Date", "Merchant", "Category", "Amount", "Status", "Receipt"],
         lambda r, y: [_iso(r, y), r.choice(["CVS PHARMACY", "SAMPLE FAMILY CLINIC", "BRIGHTSMILE DENTAL", "VISION CENTER"]), r.choice(["Medical", "Pharmacy", "Dental", "Vision"]), _amt(r, 5, 900), r.choice(["Posted", "Pending"]), r.choice(["Uploaded", "Missing"])]),
    ],
    "CRYPTO_TAX_REPORT": [
        (["Timestamp", "Transaction Type", "Asset", "Quantity Transacted", "Spot Price at Transaction", "Subtotal", "Total (inclusive of fees)", "Fees"],
         lambda r, y: [f"{_iso(r, y)}T{r.randint(0, 23):02d}:{r.randint(0, 59):02d}:00Z", r.choice(["Buy", "Sell", "Convert", "Send", "Receive", "Staking Income"]), r.choice(["BTC", "ETH", "SOL", "USDC"]), f"{r.uniform(0.0001, 20):.6f}", _amt(r, 1, 70000), _amt(r, 1, 9000), _amt(r, 1, 9100), _amt(r, 0, 40)]),
        (["Date", "Sent Amount", "Sent Currency", "Received Amount", "Received Currency", "Fee Amount", "Fee Currency", "Tag"],
         lambda r, y: [_iso(r, y), f"{r.uniform(0.01, 5000):.4f}", r.choice(["USD", "BTC", "ETH"]), f"{r.uniform(0.0001, 5000):.6f}", r.choice(["ETH", "SOL", "USD"]), f"{r.uniform(0, 5):.4f}", "USD", r.choice(["", "staking", "airdrop", "trade"])]),
        (["Asset", "Date Acquired", "Date Sold", "Proceeds", "Cost Basis", "Gain (Loss)", "Holding Period"],
         lambda r, y: [r.choice(["BTC", "ETH", "SOL"]), _iso(r, y - 1), _iso(r, y), _amt(r, 10, 20000), _amt(r, 10, 20000), _amt(r, 1, 9000, 0.4), r.choice(["Short-term", "Long-term"])]),
    ],
    "PROFIT_AND_LOSS_STATEMENT": [
        (["Account", "Q1", "Q2", "Q3", "Q4", "Total"],
         lambda r, y: [r.choice(["Total Revenue", "Sales", "Cost of Goods Sold", "Gross Profit", "Payroll Expenses", "Rent", "Marketing", "Net Income"])] + [_amt(r, 100, 90000) for _ in range(5)]),
        (["Category", "Jan", "Feb", "Mar", "YTD"],
         lambda r, y: [r.choice(["Income", "Service revenue", "COGS", "Operating expenses", "Contractors", "Software", "Net operating income"])] + [_amt(r, 100, 30000) for _ in range(4)]),
    ],
}
PREAMBLES = {
    "BANK_STATEMENT": ["Everyday Checking ...{a}", "Savings Account XXXX{a} - transactions", "Account History: Checking"],
    "CREDIT_CARD_STATEMENT": ["Card ending in {a} - Activity", "Credit Card Transactions", "Rewards Visa ...{a}"],
    "MORTGAGE_STATEMENT": ["Mortgage loan {a} - payment history", "Home Loan Activity", "Loan History - Mortgage"],
    "LOAN_STATEMENT": ["Loan {a} payment history", "Auto Loan Activity", "Student Loan Transactions", "Personal Loan History"],
    "BROKERAGE_STATEMENT": ["Positions as of {d}", "Brokerage Account ...{a} - Activity", "Portfolio Positions"],
    "RETIREMENT_ACCOUNT_STATEMENT": ["401(k) Plan contribution history", "IRA ...{a} Positions", "Retirement Plan Activity"],
    "HSA_ACCOUNT_STATEMENT": ["HSA Activity", "Health Savings Account ...{a} transactions", "HSA Claims and Contributions"],
    "CRYPTO_TAX_REPORT": ["Transaction history export", "Crypto gains and losses - {y}", "Exchange account statement"],
    "PROFIT_AND_LOSS_STATEMENT": ["{b} - Profit and Loss - {y}", "Income statement by month", "P&L Summary {y}"],
}


def raw_export(rng: random.Random, year: int, label: str) -> tuple[list[tuple], str]:
    """A downloaded account export: optional preamble, header row, rows."""
    header, row = rng.choice(EXPORTS[label])
    items: list[tuple] = []
    if rng.random() < 0.6:
        pre = rng.choice(PREAMBLES[label]).format(a=rng.randint(1000, 9999), d=_iso(rng, year), y=year,
                                                  b=rng.choice(BUSINESSES))
        items.append(("title", pre))
    if rng.random() < 0.3:
        items.append(("line", f"Downloaded {_iso(rng, year)}"))
    items.append(("table", header, [row(rng, year) for _ in range(rng.randint(3, 9))]))
    return items, "raw_export"


def with_exports(label: str, gen):
    """Wrap a statement generator so a quarter of its rows are raw exports."""
    def wrapped(rng: random.Random, year: int) -> tuple[list[tuple], str]:
        if rng.random() < 0.25:
            return raw_export(rng, year, label)
        return gen(rng, year)
    return wrapped


for _label in EXPORTS:
    GENERATORS[_label] = with_exports(_label, GENERATORS[_label])