Skip to main content

btctax_cli/
render.rs

1//! Text rendering of CLI outputs (FR9 verify, FR4 report/show) + FR10 CSV export. Pure string-building
2//! over engine data — the CLI displays; the engine computes (NFR4/NFR5).
3use crate::config::CliConfig;
4use btctax_adapters::FileReport;
5use btctax_core::conventions::{tax_date, Sat, Usd, TRANSITION_DATE};
6use btctax_core::persistence::ImportReport;
7use btctax_core::DonationDetails;
8use btctax_core::{
9    conservation_report, disposal_compliance, form_8283, form_8949, schedule_d,
10    year_donation_deduction, BasisSource, Blocker, BlockerKind, ComplianceStatus,
11    ConservationReport, DisposalCompliance, DisposalLeg, DisposeKind, EventId, EventPayload,
12    Form8283HowAcquired, Form8283Section, Form8949Box, Form8949Part, GiftZone, HarvestReport,
13    HarvestStatus, HarvestTarget, InboundClass, IncomeKind, LedgerEvent, LedgerState, LotMethod,
14    LtcgBracket, OutflowClass, RemovalKind, RemovalLeg, ScheduleDTotals, SeTaxResult, SellReport,
15    SellStatus, Severity, TaxDate, Term, WalletId,
16};
17use btctax_store::fsperms;
18use csv::Writer;
19use std::collections::{BTreeMap, BTreeSet};
20use std::fmt::Write as _;
21use std::path::Path;
22
23// ── Money formatting helper ──────────────────────────────────────────────────────────────────────
24
25/// Format any `Decimal` money value as exactly 2 decimal places (e.g. "0.00", "1747.50").
26///
27/// Load-bearing figures (`ltcg_tax`, `niit`, `total_federal_tax_attributable`) are always
28/// `round_cents`-scaled (scale 2) so they already print with cents. Descriptive level fields
29/// (`st_net`, `lt_net`, `carryforward`, `loss_deduction`, etc.) inherit the source `Decimal`
30/// scale and may print as "7000" or "0" without explicit 2dp formatting. This helper ensures
31/// every dollar figure in the tax report renders consistently with 2 decimal places.
32///
33/// **Equality is unaffected** — this is display only. The underlying `Decimal` value is
34/// unchanged; only the `Display` string gains the forced 2dp format.
35fn fmt_money(d: btctax_core::conventions::Usd) -> String {
36    format!("{d:.2}")
37}
38
39// ── Stable CSV/display tags for core enums ──────────────────────────────────────────────────────
40// These are free functions (not inherent methods) because the CLI crate cannot add methods to
41// core types. Values are human-readable and STABLE — changing them breaks the CSV contract.
42
43fn basis_source_tag(bs: BasisSource) -> &'static str {
44    match bs {
45        BasisSource::ExchangeProvided => "exchange",
46        BasisSource::ComputedFromCost => "cost",
47        BasisSource::FmvAtIncome => "income_fmv",
48        BasisSource::CarriedFromTransfer => "transferred",
49        BasisSource::GiftCarryover => "gift_carryover",
50        BasisSource::GiftFmvFallback => "gift_fmv_fallback",
51        BasisSource::SafeHarborAllocated => "safe_harbor",
52        BasisSource::ReconstructedPerWallet => "reconstructed",
53        BasisSource::SelfTransferInbound => "self_transfer_in",
54        BasisSource::EstimatedConservative => "estimated_conservative",
55    }
56}
57
58/// Pseudo-reconcile (sub-project 2, [R0-I4]): the ON-SCREEN-ONLY `[PSEUDO]` marker for a row whose
59/// existence or basis traces to a synthetic (non-persisted) default. Driven by the DEDICATED `pseudo`
60/// bool on `Lot`/`DisposalLeg`/`RemovalLeg` — NEVER a `BasisSource` variant (which the CSV writers emit
61/// via `basis_source_tag`, and would LEAK "PSEUDO" into lots.csv). The CSV/form writers OMIT this marker
62/// entirely (they never call this helper), so it can never reach any export file (the ★ headline guard).
63fn pseudo_tag(pseudo: bool) -> &'static str {
64    if pseudo {
65        " [PSEUDO]"
66    } else {
67        ""
68    }
69}
70
71fn dispose_kind_tag(dk: DisposeKind) -> &'static str {
72    match dk {
73        DisposeKind::Sell => "sell",
74        DisposeKind::Spend => "spend",
75    }
76}
77
78fn income_kind_tag(ik: IncomeKind) -> &'static str {
79    match ik {
80        IncomeKind::Mining => "mining",
81        IncomeKind::Staking => "staking",
82        IncomeKind::Interest => "interest",
83        IncomeKind::Airdrop => "airdrop",
84        IncomeKind::Reward => "reward",
85    }
86}
87
88/// UX-P4-7: SCREEN-ONLY human summary of an `InboundClass` decision payload (income / received gift /
89/// self-transfer). Replaces the raw `{:?}` Debug dump (`SelfTransferMine { basis: Some(19000.00),
90/// acquired_at: Some(2026-01-01) }`) that the CLI bulk-void preview + TUI void list truncated
91/// mid-field. Like `pseudo_tag` [R0-I4], this is for the terminal ONLY — the CSV/form writers MUST
92/// NOT call it (they emit stable machine tags via `*_tag`), so no human phrasing can leak into an
93/// export file.
94pub fn describe_inbound_class(c: &InboundClass) -> String {
95    match c {
96        InboundClass::Income {
97            kind,
98            fmv,
99            business,
100        } => {
101            let mut s = format!("income {}", income_kind_tag(*kind));
102            if let Some(v) = fmv {
103                let _ = write!(s, ", fmv ${}", fmt_money(*v));
104            }
105            if *business {
106                s.push_str(", business");
107            }
108            s
109        }
110        InboundClass::GiftReceived {
111            donor_basis,
112            donor_acquired_at,
113            fmv_at_gift,
114        } => {
115            let mut s = format!("gift received, fmv ${}", fmt_money(*fmv_at_gift));
116            if let Some(b) = donor_basis {
117                let _ = write!(s, ", donor-basis ${}", fmt_money(*b));
118            }
119            if let Some(d) = donor_acquired_at {
120                let _ = write!(s, ", donor-acquired {d}");
121            }
122            s
123        }
124        InboundClass::SelfTransferMine { basis, acquired_at } => {
125            // `None` is a defaulted field (zero basis / 1yr+1day-before-receipt date), NOT the Debug
126            // `None` — name it "default" so the void preview is legible.
127            let basis_s = match basis {
128                Some(v) => format!("${}", fmt_money(*v)),
129                None => "default".to_string(),
130            };
131            let acq_s = match acquired_at {
132                Some(d) => d.to_string(),
133                None => "default".to_string(),
134            };
135            format!("self-transfer (mine), basis {basis_s}, acquired {acq_s}")
136        }
137    }
138}
139
140/// UX-P4-7: SCREEN-ONLY human summary of an `OutflowClass` decision payload. Same screen-only rule as
141/// [`describe_inbound_class`] — never called by a CSV/form writer.
142pub fn describe_outflow_class(c: &OutflowClass) -> String {
143    match c {
144        OutflowClass::Dispose { kind } => dispose_kind_tag(*kind).to_string(),
145        OutflowClass::GiftOut => "gift".to_string(),
146        OutflowClass::Donate { appraisal_required } => {
147            if *appraisal_required {
148                "donate (appraisal required)".to_string()
149            } else {
150                "donate".to_string()
151            }
152        }
153    }
154}
155
156fn gift_zone_tag(gz: GiftZone) -> &'static str {
157    match gz {
158        GiftZone::Gain => "gain",
159        GiftZone::Loss => "loss",
160        GiftZone::NoGainNoLoss => "no_gain_no_loss",
161    }
162}
163
164fn removal_kind_tag(rk: RemovalKind) -> &'static str {
165    match rk {
166        RemovalKind::Gift => "gift",
167        RemovalKind::Donation => "donation",
168    }
169}
170
171/// Stable term tag: "long" or "short" (not the Debug "LongTerm"/"ShortTerm").
172fn term_tag(t: Term) -> &'static str {
173    match t {
174        Term::ShortTerm => "short",
175        Term::LongTerm => "long",
176    }
177}
178
179/// Stable Form 8949 part tag: "ST" (Part I) / "LT" (Part II). STABLE — part of the form8949.csv contract.
180fn form8949_part_tag(p: Form8949Part) -> &'static str {
181    match p {
182        Form8949Part::ShortTerm => "ST",
183        Form8949Part::LongTerm => "LT",
184    }
185}
186
187/// Stable Form 8949 box tag: pre-TY2025 securities boxes "C" (ST) / "F" (LT), and from TY2025 the
188/// digital-asset boxes "I" (ST) / "L" (LT) — the conservative "not reported on a 1099-B / 1099-DA"
189/// default (D4). We never emit the 1099-reported boxes (A/B/D/E; G/H/J/K): the model carries no
190/// 1099 basis-reported signal.
191fn form8949_box_tag(b: Form8949Box) -> &'static str {
192    match b {
193        Form8949Box::C => "C",
194        Form8949Box::F => "F",
195        Form8949Box::I => "I",
196        Form8949Box::L => "L",
197    }
198}
199
200/// Stable Form 8283 section tag: "A" (deduction ≤ $5,000) / "B" (> $5,000). STABLE — part of the
201/// form8283.csv contract.
202fn form8283_section_tag(s: Form8283Section) -> &'static str {
203    match s {
204        Form8283Section::A => "A",
205        Form8283Section::B => "B",
206    }
207}
208
209/// Stable Form 8283 "how acquired" tag: literal Form 8283 categories (NOT the internal BasisSource
210/// tags). STABLE — part of the form8283.csv contract.
211fn form8283_how_acquired_tag(h: Form8283HowAcquired) -> &'static str {
212    match h {
213        Form8283HowAcquired::Purchased => "Purchased",
214        Form8283HowAcquired::Gift => "Gift",
215        Form8283HowAcquired::Other => "Other",
216        Form8283HowAcquired::Review => "Review",
217    }
218}
219
220/// Stable compliance-status display string, used in `render_verify` and optimizer output
221/// in place of `{:?}` (which would expose unstable Rust Debug formatting).
222///
223/// Values:
224/// - `standing_order:<date>` — in-force standing order effective from `<date>` (YYYY-MM-DD).
225/// - `contemporaneous`       — `LotSelection` recorded on or before the day of sale.
226/// - `attested_recording`    — Mode-1-persisted selection backed by contemporaneous-ID attestation (§C.2).
227/// - `non_compliant`         — no adequate identification; FIFO is the defensible filing position.
228fn compliance_status_tag(cs: &ComplianceStatus) -> String {
229    match cs {
230        ComplianceStatus::StandingOrder { effective_from } => {
231            format!("standing_order:{effective_from}")
232        }
233        ComplianceStatus::Contemporaneous => "contemporaneous".into(),
234        ComplianceStatus::AttestedRecording => "attested_recording".into(),
235        ComplianceStatus::NonCompliant => "non_compliant".into(),
236    }
237}
238
239/// FR1/FR2: per-source drop/unclassified counts + the append/duplicate/conflict tally.
240pub fn render_file_reports(reports: &[FileReport], import: &ImportReport) -> String {
241    let mut out = String::new();
242    let _ = writeln!(out, "Import:");
243    for r in reports {
244        let _ = writeln!(
245            out,
246            "  {} [{}]: parsed {} rows -> {} BTC events ({} dropped no-BTC, {} unclassified)",
247            r.source.tag(),
248            r.label,
249            r.parsed_rows,
250            r.btc_events,
251            r.dropped_no_btc,
252            r.unclassified
253        );
254    }
255    let _ = writeln!(
256        out,
257        "  appended {} | duplicates {} | NEW import-conflicts {}",
258        import.appended, import.duplicates, import.conflicts
259    );
260    if import.conflicts > 0 {
261        let _ = writeln!(
262            out,
263            "  ! resolve conflicts with `reconcile accept-conflict <id>` or `reject-conflict <id>` (see `verify`)"
264        );
265    }
266    out
267}
268
269/// `exchange:provider:account` | `self:label` (the same grammar `eventref::parse_wallet_id` accepts).
270pub fn wallet_label(w: &WalletId) -> String {
271    match w {
272        WalletId::Exchange { provider, account } => format!("exchange:{provider}:{account}"),
273        WalletId::SelfCustody { label } => format!("self:{label}"),
274    }
275}
276
277/// UX-P4-9: the shared "insufficient balance" message for a `what-if sell`/`harvest` whose wallet
278/// pool cannot cover the sale. Names the AVAILABLE balance, the wallet, and the as-of date so the
279/// refusal is legible; `available == 0` is the honest "no BTC" case (an empty wallet), distinct from
280/// mere insufficiency (lots exist but fall short). Used by BOTH the CLI (`cmd::whatif::map_whatif_err`)
281/// and the interactive TUI panel (`btctax_tui::whatif_panel::refusal_message`) so the two surfaces
282/// read identically. SCREEN-ONLY.
283pub fn no_lots_message(wallet: &WalletId, at: TaxDate, available: Sat, requested: Sat) -> String {
284    if available == 0 {
285        format!("no BTC available in {} as of {}", wallet_label(wallet), at)
286    } else {
287        format!(
288            "only {} BTC available in {} as of {} (requested {} BTC)",
289            fmt_btc(available),
290            wallet_label(wallet),
291            at,
292            fmt_btc(requested),
293        )
294    }
295}
296
297fn disposal_year(d: &btctax_core::Disposal) -> i32 {
298    d.disposed_at.year()
299}
300
301/// FR4 render: holdings (always current) + realized disposals/removals/income (year-filtered).
302pub fn render_report(state: &LedgerState, year: Option<i32>) -> String {
303    let mut out = String::new();
304    let yr = |y: i32| year.is_none_or(|f| f == y); // year filter; None => all (is_none_or stable since 1.82)
305
306    let _ = writeln!(out, "Holdings (per wallet):");
307    if state.holdings_by_wallet.is_empty() {
308        let _ = writeln!(out, "  none");
309    }
310    for (w, sat) in &state.holdings_by_wallet {
311        let _ = writeln!(out, "  {}: {} sat", wallet_label(w), sat);
312    }
313    // UX-P4-6: surface unreconciled transfer sats in the holdings view (BTC unit) so `report` no
314    // longer hides what `verify` alone reported. Shown only when sats are actually pending.
315    if state.stats.sigma_pending > 0 {
316        let n = state.pending_reconciliation.len();
317        let plural = if n == 1 { "transfer" } else { "transfers" };
318        let _ = writeln!(
319            out,
320            "  Pending: {} BTC ({n} unreconciled {plural} — see `btctax verify`)",
321            fmt_btc(state.stats.sigma_pending),
322        );
323    }
324
325    let _ = writeln!(out, "Lots:");
326    if state.lots.is_empty() {
327        let _ = writeln!(out, "  none");
328    }
329    for l in &state.lots {
330        let _ = writeln!(
331            out,
332            "  {}#{} {} remaining {} sat | basis {} ({}){}{}",
333            l.lot_id.origin_event_id.canonical(),
334            l.lot_id.split_sequence,
335            wallet_label(&l.wallet),
336            l.remaining_sat,
337            l.usd_basis,
338            basis_source_tag(l.basis_source),
339            if l.basis_pending {
340                " [basis pending]"
341            } else {
342                ""
343            },
344            pseudo_tag(l.pseudo),
345        );
346    }
347
348    let label = match year {
349        Some(y) => format!("(year {y})"),
350        None => "(all years)".to_string(),
351    };
352
353    let disposals: Vec<_> = state
354        .disposals
355        .iter()
356        .filter(|d| yr(disposal_year(d)))
357        .collect();
358    if disposals.is_empty() {
359        let _ = writeln!(out, "Disposals {}: none", label);
360    } else {
361        let _ = writeln!(out, "Disposals {}:", label);
362        for d in disposals {
363            let _ = writeln!(
364                out,
365                "  {} @ {} ({})",
366                dispose_kind_tag(d.kind),
367                d.disposed_at,
368                d.event.canonical()
369            );
370            for leg in &d.legs {
371                render_disposal_leg(&mut out, leg);
372            }
373        }
374    }
375
376    let removals: Vec<_> = state
377        .removals
378        .iter()
379        .filter(|r| yr(r.removed_at.year()))
380        .collect();
381    if removals.is_empty() {
382        let _ = writeln!(out, "Removals {}: none", label);
383    } else {
384        let _ = writeln!(out, "Removals {}:", label);
385        for r in removals {
386            let deduction_tag = match r.claimed_deduction {
387                Some(d) => format!(" [claimed deduction {}]", fmt_money(d)),
388                None => String::new(),
389            };
390            let _ = writeln!(
391                out,
392                "  {} @ {} ({}){}",
393                removal_kind_tag(r.kind),
394                r.removed_at,
395                r.event.canonical(),
396                deduction_tag
397            );
398            for leg in &r.legs {
399                render_removal_leg(&mut out, leg);
400            }
401        }
402    }
403
404    let income: Vec<_> = state
405        .income_recognized
406        .iter()
407        .filter(|i| yr(i.recognized_at.year()))
408        .collect();
409    if income.is_empty() {
410        let _ = writeln!(out, "Income {}: none", label);
411    } else {
412        let _ = writeln!(out, "Income {}:", label);
413        for i in income {
414            let _ = writeln!(
415                out,
416                "  {} @ {} {} sat = {} USD{}{}",
417                income_kind_tag(i.kind),
418                i.recognized_at,
419                i.sat,
420                i.usd_fmv,
421                if i.business { " [business]" } else { "" },
422                pseudo_tag(i.pseudo), // [R0-I2] a pseudo daily-close income FMV is flagged on screen
423            );
424        }
425    }
426
427    // Per-year charitable-deduction total (Schedule A itemized; pre-§170(b) AGI limits).
428    // Σ claimed_deduction over Donation removals in the year-filtered window.
429    let charitable_total: btctax_core::conventions::Usd = state
430        .removals
431        .iter()
432        .filter(|r| yr(r.removed_at.year()) && r.kind == RemovalKind::Donation)
433        .filter_map(|r| r.claimed_deduction)
434        .sum();
435    let _ = writeln!(
436        out,
437        "Charitable deduction {} (Schedule A itemized) — BEFORE §170(b) AGI limits / carryover: {}",
438        label,
439        fmt_money(charitable_total)
440    );
441
442    out
443}
444
445fn render_disposal_leg(out: &mut String, leg: &DisposalLeg) {
446    let zone = leg
447        .gift_zone
448        .map(|z| format!(" gift-zone {}", gift_zone_tag(z)))
449        .unwrap_or_default();
450    let _ = writeln!(
451        out,
452        "    {} sat: proceeds {} basis {} gain {} {}{}{}",
453        leg.sat,
454        leg.proceeds,
455        leg.basis,
456        leg.gain,
457        term_tag(leg.term),
458        zone,
459        pseudo_tag(leg.pseudo),
460    );
461}
462
463fn render_removal_leg(out: &mut String, leg: &RemovalLeg) {
464    let _ = writeln!(
465        out,
466        "    {} sat: basis {} fmv {} {} (zero gain){}",
467        leg.sat,
468        leg.basis,
469        leg.fmv_at_transfer,
470        term_tag(leg.term),
471        pseudo_tag(leg.pseudo),
472    );
473}
474
475// ── FR9 verify ──────────────────────────────────────────────────────────────────────────────────
476
477/// Stable display tag for `FilingStatus` (lowercase, matches the CLI value-enum strings).
478///
479/// Values: "single" | "mfj" | "mfs" | "hoh" | "qss". These mirror the `FilingStatusArg`
480/// `ValueEnum` strings accepted by `--filing-status`, so the `tax-profile --show` output
481/// is round-trip-parseable via the same flag.
482pub fn filing_status_tag(fs: btctax_core::FilingStatus) -> &'static str {
483    use btctax_core::FilingStatus::*;
484    match fs {
485        Single => "single",
486        Mfj => "mfj",
487        Mfs => "mfs",
488        HoH => "hoh",
489        Qss => "qss",
490    }
491}
492
493/// Stable display tag for `LotMethod` (FIFO/LIFO/HIFO — uppercase, human-readable).
494/// UX-P4-12(e): a human label for the TP8 self-transfer fee treatment, instead of the raw Debug
495/// variant name (`TreatmentC`/`TreatmentB`) leaking on screen.
496pub fn fee_treatment_display(t: btctax_core::FeeTreatment) -> &'static str {
497    match t {
498        btctax_core::FeeTreatment::TreatmentC => "non-taxable, basis carries (TP8 c)",
499        btctax_core::FeeTreatment::TreatmentB => "taxable mini-disposition (TP8 b)",
500    }
501}
502
503pub fn lot_method_display(m: LotMethod) -> &'static str {
504    match m {
505        LotMethod::Fifo => "FIFO",
506        LotMethod::Lifo => "LIFO",
507        LotMethod::Hifo => "HIFO",
508    }
509}
510
511/// One entry in the `MethodElection` standing-order history reported by `verify`.
512#[derive(Debug, Clone)]
513pub struct ElectionLine {
514    pub recorded: TaxDate,
515    pub effective_from: TaxDate,
516    pub method: LotMethod,
517    /// `None` = a VAULT-WIDE (global) election; `Some(w)` = scoped to that exchange account only.
518    pub wallet: Option<WalletId>,
519    /// "in force" | "voided" | "backdated/ignored"
520    pub note: &'static str,
521}
522
523/// The set of decision targets that a `VoidDecisionEvent` has voided (for election notes + selection
524/// counting). Shared by `verify` and `config` (UX-P4-12(c)).
525pub fn voided_targets(events: &[LedgerEvent]) -> BTreeSet<EventId> {
526    events
527        .iter()
528        .filter_map(|e| match &e.payload {
529            EventPayload::VoidDecisionEvent(v) => Some(v.target_event_id.clone()),
530            _ => None,
531        })
532        .collect()
533}
534
535/// The `MethodElection` standing-order history, sorted by `decision_seq` for a stable total order;
536/// each `note` marks in-force / voided / backdated. Shared by `verify`'s Standing-orders block and
537/// `config`'s forward-method read-back (UX-P4-12(c)).
538pub fn method_election_lines(
539    events: &[LedgerEvent],
540    voided: &BTreeSet<EventId>,
541) -> Vec<ElectionLine> {
542    let mut election_events: Vec<(u64, &LedgerEvent)> = events
543        .iter()
544        .filter_map(|e| {
545            if let EventId::Decision { seq } = e.id {
546                if matches!(e.payload, EventPayload::MethodElection(_)) {
547                    return Some((seq, e));
548                }
549            }
550            None
551        })
552        .collect();
553    election_events.sort_by_key(|(s, _)| *s);
554
555    election_events
556        .iter()
557        .map(|(_, e)| {
558            let EventPayload::MethodElection(me) = &e.payload else {
559                unreachable!("filtered to MethodElection above")
560            };
561            let recorded = tax_date(e.utc_timestamp, e.original_tz);
562            let note = if voided.contains(&e.id) {
563                "voided"
564            } else if me.effective_from < TRANSITION_DATE || me.effective_from < recorded {
565                "backdated/ignored"
566            } else {
567                "in force"
568            };
569            ElectionLine {
570                recorded,
571                effective_from: me.effective_from,
572                method: me.method,
573                wallet: me.wallet.clone(),
574                note,
575            }
576        })
577        .collect()
578}
579
580/// Structured FR9 outcome (so tests assert on data, not stdout, and `main` keys the exit code).
581#[derive(Debug, Clone)]
582pub struct VerifyReport {
583    pub conservation: ConservationReport,
584    pub hard: Vec<Blocker>,
585    pub advisory: Vec<Blocker>,
586    pub pending: usize,
587    pub unknown_basis_inbounds: usize,
588    pub safe_harbor: String,
589    /// Task 8: declared `pre2025_method` from the CLI config (attested or not).
590    pub declared_pre2025_method: LotMethod,
591    pub pre2025_method_attested: bool,
592    /// Task 8: standing-order history (all `MethodElection` decisions, sorted by decision_seq).
593    pub elections: Vec<ElectionLine>,
594    /// Task 8: count of non-voided `LotSelection` decisions.
595    pub selection_count: usize,
596    /// Task 8: per-disposal compliance (post-2025 only).
597    pub compliance: Vec<DisposalCompliance>,
598}
599
600impl VerifyReport {
601    /// Non-zero exit condition (§7.1): any open hard blocker. (Conservation imbalance always coincides
602    /// with a hard blocker — `uncovered_disposal` — so the hard list is the single source of truth.)
603    pub fn has_hard_blockers(&self) -> bool {
604        !self.hard.is_empty()
605    }
606}
607
608/// 2025-transition status for display: detect effective Path B via lot basis-source, then
609/// advisory blockers (§7.4). Prefer the effective-state signal (SafeHarborAllocated lots) over
610/// the advisory blocker so the attest happy-path (void-prior → re-attest) is not
611/// misreported as time-barred when a stale SafeHarborTimebar advisory remains in state.blockers
612/// from the now-voided inert allocation.
613///
614/// Fix: also OR in disposal/removal legs for SafeHarborAllocated basis-source. When ALL
615/// Path-B allocated lots are fully consumed (remaining_sat==0 → filtered out by `finalize`),
616/// `state.lots` has no SafeHarborAllocated entries, but the disposed/removed legs still carry
617/// the correct basis_source and prove Path B was effective at fold time.
618fn safe_harbor_status(state: &LedgerState, _events: &[LedgerEvent]) -> String {
619    // Effective Path B: seeded SafeHarborAllocated lots at the 2025-01-01 boundary.
620    // Check remaining lots, disposal legs, and removal legs (all three carry basis_source).
621    let effective_path_b = state
622        .lots
623        .iter()
624        .any(|l| l.basis_source == BasisSource::SafeHarborAllocated)
625        || state.disposals.iter().any(|d| {
626            d.legs
627                .iter()
628                .any(|leg| leg.basis_source == BasisSource::SafeHarborAllocated)
629        })
630        || state.removals.iter().any(|r| {
631            r.legs
632                .iter()
633                .any(|leg| leg.basis_source == BasisSource::SafeHarborAllocated)
634        });
635    let unconservable = state
636        .blockers
637        .iter()
638        .any(|b| b.kind == BlockerKind::SafeHarborUnconservable);
639    let timebar = state
640        .blockers
641        .iter()
642        .any(|b| b.kind == BlockerKind::SafeHarborTimebar);
643    // SafeHarborUnconservable is a hard blocker; resolve never seeds effective lots when it fires,
644    // so unconservable wins unconditionally. effective_path_b next: if the engine is on Path B
645    // (lots are present), report it regardless of any stale timebar advisory.
646    if unconservable {
647        "Path B allocation FAILS conservation/eligibility (hard, §7.4) — fix the allocation"
648            .to_string()
649    } else if effective_path_b {
650        "Path B safe-harbor allocation is effective (§7.4)".to_string()
651    } else if timebar {
652        "Path B time-barred -> using Path A (advisory); `reconcile safe-harbor attest` if timely in your books".to_string()
653    } else {
654        "Path A (actual per-wallet reconstruction; default, no election)".to_string()
655    }
656}
657
658pub fn build_verify(state: &LedgerState, events: &[LedgerEvent], cli: &CliConfig) -> VerifyReport {
659    let conservation = conservation_report(state);
660    let mut hard = Vec::new();
661    let mut advisory = Vec::new();
662    for b in &state.blockers {
663        match b.kind.severity() {
664            Severity::Hard => hard.push(b.clone()),
665            Severity::Advisory => advisory.push(b.clone()),
666        }
667    }
668    let unknown_basis_inbounds = state
669        .blockers
670        .iter()
671        .filter(|b| b.kind == BlockerKind::UnknownBasisInbound)
672        .count();
673
674    // Build the voided set (for election notes and selection counting).
675    let voided = voided_targets(events);
676
677    // Build election history (NFR4: sorted by decision_seq for a stable total order).
678    let elections = method_election_lines(events, &voided);
679
680    // Count non-voided LotSelection decisions.
681    // Note: a `Decision`-id guard is intentionally omitted — `LotSelection` payloads are
682    // exclusively carried by `EventId::Decision` events (appended via `append_decision` in the
683    // CLI); filtering by payload alone is equivalent and sufficient.
684    let selection_count = events
685        .iter()
686        .filter(|e| matches!(e.payload, EventPayload::LotSelection(_)) && !voided.contains(&e.id))
687        .count();
688
689    // Per-disposal compliance (§A.5): side-effect-free projection.
690    let compliance = disposal_compliance(events, state);
691
692    VerifyReport {
693        conservation,
694        hard,
695        advisory,
696        pending: state.pending_reconciliation.len(),
697        unknown_basis_inbounds,
698        safe_harbor: safe_harbor_status(state, events),
699        declared_pre2025_method: cli.pre2025_method,
700        pre2025_method_attested: cli.pre2025_method_attested,
701        elections,
702        selection_count,
703        compliance,
704    }
705}
706
707/// FR10: write the projected ledger as CSV (the NFR2 plaintext exception). One row per disposal/removal
708/// leg (flattened) + one per lot/income record. Exact values (Decimal/i64) as strings (NFR5).
709/// Each CSV is opened via `fsperms::open_owner_only` (0o600 on Unix) so decrypted PII matches the
710/// hardened permissions already applied to `snapshot.sqlite` by the store crate. The out-dir is
711/// created owner-only (0o700) if absent; when the dir PRE-EXISTS, open_owner_only still forces 0o600
712/// on each new CSV file (the hole that `Writer::from_path` + umask would leave).
713///
714/// The `lots`/`disposals`/`removals`/`income` CSVs are all-years (a full projection dump). The
715/// **Form 8949 + Schedule D** filing artifacts are inherently per-tax-year (P2-B): when `tax_year`
716/// is `Some(y)`, `form8949.csv` + `schedule_d.csv` are additionally written, year-scoped to `y`;
717/// when `None`, they are omitted.
718pub fn write_csv_exports(
719    out_dir: &Path,
720    state: &LedgerState,
721    tax_year: Option<i32>,
722    se_result: Option<&SeTaxResult>,
723    donation_details: &BTreeMap<EventId, DonationDetails>,
724) -> Result<(), crate::CliError> {
725    fsperms::mkdir_owner_only(out_dir)?;
726
727    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("lots.csv"))?);
728    w.write_record([
729        "origin_event",
730        "split",
731        "wallet",
732        "acquired_at",
733        "remaining_sat",
734        "usd_basis",
735        "basis_source",
736        "basis_pending",
737    ])?;
738    for l in &state.lots {
739        w.write_record([
740            l.lot_id.origin_event_id.canonical(),
741            l.lot_id.split_sequence.to_string(),
742            wallet_label(&l.wallet),
743            l.acquired_at.to_string(),
744            l.remaining_sat.to_string(),
745            l.usd_basis.to_string(),
746            basis_source_tag(l.basis_source).to_string(),
747            l.basis_pending.to_string(),
748        ])?;
749    }
750    w.flush()?;
751
752    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("disposals.csv"))?);
753    w.write_record([
754        "event",
755        "kind",
756        "disposed_at",
757        "lot",
758        "sat",
759        "proceeds",
760        "basis",
761        "gain",
762        "term",
763        "gift_zone",
764        "acquired_at",
765        "wallet",
766    ])?;
767    for d in &state.disposals {
768        for leg in &d.legs {
769            w.write_record([
770                d.event.canonical(),
771                dispose_kind_tag(d.kind).to_string(),
772                d.disposed_at.to_string(),
773                format!(
774                    "{}#{}",
775                    leg.lot_id.origin_event_id.canonical(),
776                    leg.lot_id.split_sequence
777                ),
778                leg.sat.to_string(),
779                leg.proceeds.to_string(),
780                leg.basis.to_string(),
781                leg.gain.to_string(),
782                term_tag(leg.term).to_string(),
783                leg.gift_zone
784                    .map(|z| gift_zone_tag(z).to_string())
785                    .unwrap_or_default(),
786                leg.acquired_at.to_string(),
787                wallet_label(&leg.wallet),
788            ])?;
789        }
790    }
791    w.flush()?;
792
793    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("removals.csv"))?);
794    // claimed_deduction: §170(e)(1)(A) deduction amount (pre-§170(b) AGI limits) for Donation
795    // rows; empty for Gift rows. See Removal.claimed_deduction in btctax-core/src/state.rs.
796    // Multi-leg donations: the value is a per-REMOVAL total shown on the FIRST leg row only;
797    // subsequent leg rows carry an empty cell so a naive SUM() equals the correct per-donation
798    // total (no double-counting). Do not divide across legs — that would create rounding artifacts.
799    // donee: free-form donee label (Chunk 2); empty when not set.
800    w.write_record([
801        "event",
802        "kind",
803        "removed_at",
804        "lot",
805        "sat",
806        "basis",
807        "fmv_at_transfer",
808        "term",
809        "acquired_at",
810        "claimed_deduction",
811        "donee",
812    ])?;
813    for r in &state.removals {
814        let deduction_first = r
815            .claimed_deduction
816            .map(|d| d.to_string())
817            .unwrap_or_default();
818        let donee_cell = r.donee.clone().unwrap_or_default();
819        for (leg_idx, leg) in r.legs.iter().enumerate() {
820            // Emit claimed_deduction only on leg 0; leave empty on subsequent legs so SUM()
821            // over the column equals the true per-donation total (not N-legs × deduction).
822            let deduction_cell: &str = if leg_idx == 0 { &deduction_first } else { "" };
823            w.write_record([
824                r.event.canonical(),
825                removal_kind_tag(r.kind).to_string(),
826                r.removed_at.to_string(),
827                format!(
828                    "{}#{}",
829                    leg.lot_id.origin_event_id.canonical(),
830                    leg.lot_id.split_sequence
831                ),
832                leg.sat.to_string(),
833                leg.basis.to_string(),
834                leg.fmv_at_transfer.to_string(),
835                term_tag(leg.term).to_string(),
836                leg.acquired_at.to_string(),
837                deduction_cell.to_string(),
838                donee_cell.clone(),
839            ])?;
840        }
841    }
842    w.flush()?;
843
844    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("income.csv"))?);
845    w.write_record([
846        "event",
847        "kind",
848        "recognized_at",
849        "sat",
850        "usd_fmv",
851        "business",
852    ])?;
853    for i in &state.income_recognized {
854        w.write_record([
855            i.event.canonical(),
856            income_kind_tag(i.kind).to_string(),
857            i.recognized_at.to_string(),
858            i.sat.to_string(),
859            i.usd_fmv.to_string(),
860            i.business.to_string(),
861        ])?;
862    }
863    w.flush()?;
864
865    // P2-B: per-tax-year Form 8949 + Schedule D filing artifacts (year-scoped; omitted when None).
866    // P2-C: per-tax-year Form 8283 donation artifact rides the same year-scoped block.
867    if let Some(year) = tax_year {
868        write_form8949_csv(out_dir, state, year)?;
869        write_schedule_d_csv(out_dir, state, year)?;
870        write_form8283_csv(out_dir, state, year, donation_details)?;
871        write_basis_methodology_txt(out_dir, state, year)?; // P7 / D-4 (mandatory when a tranche is filed)
872                                                            // P2-D / Chunk B: standalone Schedule SE §1401 figure — written only when there IS SE tax
873                                                            // (a computed SeTaxResult); omitted when there is no business SE income OR when the year
874                                                            // is fully expensed (expenses ≥ gross → net_se == 0 → compute_se_tax returns None — [N4]).
875                                                            // The "fully expensed" render advisory (render_schedule_se) surfaces the liability status
876                                                            // ("no §1401 SE tax"); the CSV writer sees None in both the no-income and fully-expensed
877                                                            // cases — same omission, different reason.
878        if let Some(se) = se_result {
879            write_schedule_se_csv(out_dir, se)?;
880        }
881    }
882    Ok(())
883}
884
885/// Write the year-scoped form artifacts for `year` into `out_dir`.
886///
887/// Creates `out_dir` owner-only (0o700) if absent (tolerant `mkdir_owner_only`, mkdir-p);
888/// each file is written via `fsperms::open_owner_only` (0o600).  Writes `form8949.csv`,
889/// `schedule_d.csv`, `form8283.csv`; `schedule_se.csv` when `se_result` is `Some`; and the
890/// mandatory `basis_methodology.txt` (P7 / D-4) when a conservative-filing tranche is in the
891/// year's filed set. The all-years dump CSVs (`lots.csv`, `disposals.csv`, `removals.csv`,
892/// `income.csv`) are NOT written; `export_snapshot` / `snapshot.sqlite` are NEVER called
893/// or written.
894///
895/// Path containment is the CALLER's job (matching `write_csv_exports` / `export_snapshot`
896/// / `backup_key`): callers must pass a freshly-created or trusted directory — this
897/// function truncates the four fixed filenames in `out_dir` (`open_owner_only` is
898/// create-or-truncate and follows symlinks). The TUI's `export.rs` satisfies this via
899/// `mkdir_owner_only_exclusive` (D2).
900pub fn write_form_csvs(
901    out_dir: &Path,
902    state: &LedgerState,
903    year: i32,
904    se_result: Option<&SeTaxResult>,
905    donation_details: &BTreeMap<EventId, DonationDetails>,
906) -> Result<(), crate::CliError> {
907    fsperms::mkdir_owner_only(out_dir)?;
908    write_form8949_csv(out_dir, state, year)?;
909    write_schedule_d_csv(out_dir, state, year)?;
910    write_form8283_csv(out_dir, state, year, donation_details)?;
911    write_basis_methodology_txt(out_dir, state, year)?; // P7 / D-4 (mandatory when a tranche is filed)
912    if let Some(se) = se_result {
913        write_schedule_se_csv(out_dir, se)?;
914    }
915    Ok(())
916}
917
918/// P7 (D-4): write the MANDATORY conservative-filing methodology disclosure (`basis_methodology.txt`,
919/// 0o600) alongside the year's form artifacts whenever a tranche is in the year's filed set. A no-tranche
920/// year writes NOTHING — the i8949 basis explanation is required only when actual cost is not used.
921/// `pub(crate)` so the `export-irs-pdf` / full-return packet writers (`cmd/admin.rs`) emit it too (I-3).
922pub(crate) fn write_basis_methodology_txt(
923    out_dir: &Path,
924    state: &LedgerState,
925    year: i32,
926) -> Result<(), crate::CliError> {
927    use std::io::Write as _;
928    if let Some(text) = btctax_core::conservative::basis_methodology(state, year) {
929        let mut file = fsperms::open_owner_only(&out_dir.join("basis_methodology.txt"))?;
930        writeln!(file, "{text}")?;
931    }
932    Ok(())
933}
934
935/// P2-D Task 2: write `schedule_se.csv` — the standalone §1401 SE-tax components for the tax year.
936/// One data row. Stable snake_case columns; exact `Decimal` string values (NFR5). 0o600 via
937/// `open_owner_only`. Written only when a `SeTaxResult` exists (business SE income present + table).
938fn write_schedule_se_csv(out_dir: &Path, se: &SeTaxResult) -> Result<(), crate::CliError> {
939    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("schedule_se.csv"))?);
940    w.write_record([
941        "net_se_earnings",
942        "se_base_9235",
943        "ss_component",
944        "medicare_component",
945        "additional_medicare_component",
946        "total_se_tax",
947        "deductible_half",
948    ])?;
949    w.write_record([
950        se.net_se.to_string(),
951        se.base.to_string(),
952        se.ss.to_string(),
953        se.medicare.to_string(),
954        se.addl.to_string(),
955        se.total.to_string(),
956        se.deductible_half.to_string(),
957    ])?;
958    w.flush()?;
959    Ok(())
960}
961
962/// The standing Section A/B aggregation note — emitted as the first (comment) line of form8283.csv
963/// and reused by any text/advisory path. Reflects the §170(f)(11)(F) year-aggregate implementation:
964/// all BTC is "similar property"; the YEAR-total BTC donation deduction determines Section A/B
965/// uniformly for all rows. CCA 202302012 confirms the readily-valued exception does not apply to
966/// crypto, so a year-aggregate > $5,000 requires a qualified appraisal.
967pub const FORM_8283_AGGREGATION_CAVEAT: &str =
968    "Section A/B reflects the \u{00a7}170(f)(11)(F) year-aggregate for similar property: all BTC \
969     donations in the year are summed (all BTC is 'similar property'); if the year-total claimed \
970     deduction exceeds $5,000 every row is Section B (qualified appraisal required), otherwise \
971     Section A. CCA 202302012: the readily-valued exception does not apply to crypto.";
972
973/// §170(f)(11)(F) year-aggregate appraisal advisory (D2) — render-time only.
974///
975/// Emits a standalone advisory when the year-aggregate claimed deduction exceeds
976/// `QUALIFIED_APPRAISAL_THRESHOLD` ($5,000, strict `>`): even if no single BTC donation exceeds
977/// $5,000, the year-aggregate may require a qualified appraisal (CCA 202302012: the readily-valued
978/// exception does not apply to crypto; all BTC is "similar property").
979///
980/// **Render-time only — does NOT enter `state.advisory` / the blocker set** (consistent with the
981/// standalone-forms pattern; the per-donation `BlockerKind::QualifiedAppraisalNote` in fold.rs
982/// is left as-is — this advisory adds the year-aggregate signal without touching the fold).
983///
984/// Delegates to `btctax_core::year_donation_deduction` — the **shared helper** that `form_8283`
985/// uses for the Section A/B decision and that `write_form8283_csv` uses for the [R0-M1] $500 floor
986/// note. This is the single source of truth: the form, the floor note, and this advisory all call
987/// the same function, making it structurally impossible for them to diverge.
988///
989/// Returns `None` when the year has no donations or the aggregate ≤ $5,000.
990pub fn render_donation_appraisal_advisory(state: &LedgerState, year: i32) -> Option<String> {
991    use btctax_core::QUALIFIED_APPRAISAL_THRESHOLD;
992    let agg = year_donation_deduction(state, year);
993    if agg <= QUALIFIED_APPRAISAL_THRESHOLD {
994        return None;
995    }
996    // N1: format both the aggregate and the threshold with the same money formatter (fmt_money →
997    // 2dp, no thousands separator) so the two dollar figures in the advisory are styled uniformly.
998    let threshold = fmt_money(QUALIFIED_APPRAISAL_THRESHOLD);
999    Some(format!(
1000        "\u{00a7}170(f)(11)(F): your {year} BTC donations aggregate ${} of claimed deduction \
1001         (> ${threshold}) \u{2014} a qualified appraisal is required for the donated BTC even if \
1002         no single donation exceeds ${threshold} (all BTC is 'similar property'; CCA 202302012 \
1003         \u{2014} no readily-valued exception for crypto).",
1004        fmt_money(agg)
1005    ))
1006}
1007
1008/// P2-C Task 2: write `form8283.csv` — one row per `Donation` `RemovalLeg` contributed in `year`.
1009/// Stable snake_case columns; exact `Decimal`/`i64` string values (NFR5). 0o600 via `open_owner_only`.
1010///
1011/// The file leads with `#`-prefixed comment lines: the standing aggregation note, and — when the
1012/// year's total noncash charitable deduction is ≤ $500 — the [R0-M1] filing-floor note that Form
1013/// 8283 is not required at that level (the rows are still emitted, informationally).
1014fn write_form8283_csv(
1015    out_dir: &Path,
1016    state: &LedgerState,
1017    year: i32,
1018    details: &BTreeMap<EventId, DonationDetails>,
1019) -> Result<(), crate::CliError> {
1020    use std::io::Write as _;
1021    let mut file = fsperms::open_owner_only(&out_dir.join("form8283.csv"))?;
1022
1023    // STANDING aggregation note — CSV header comment line (read with comment=b'#').
1024    writeln!(file, "# {FORM_8283_AGGREGATION_CAVEAT}")?;
1025
1026    // [R0-M1] $500 form-filing floor: Form 8283 is required only when total noncash contributions
1027    // for the year exceed $500. Rows are emitted regardless; add a note when the year's total
1028    // donation deduction is ≤ $500 that Form 8283 is not required at that level.
1029    // Uses btctax_core::year_donation_deduction — the shared helper (single source of truth) that
1030    // form_8283 and render_donation_appraisal_advisory also call.
1031    let total_deduction = year_donation_deduction(state, year);
1032    if total_deduction <= rust_decimal::Decimal::from(500) {
1033        writeln!(
1034            file,
1035            "# [R0-M1] The year's total noncash charitable deduction ({}) is <= $500; Form 8283 is \
1036             NOT required at that level (rows below are informational only).",
1037            fmt_money(total_deduction)
1038        )?;
1039    }
1040
1041    let mut w = Writer::from_writer(file);
1042    w.write_record([
1043        "section",
1044        "description",
1045        "how_acquired",
1046        "date_acquired",
1047        "date_contributed",
1048        "cost_basis",
1049        "fmv",
1050        "claimed_deduction",
1051        "fmv_method",
1052        "donee",
1053        "appraiser",
1054        "needs_review",
1055        // NEW Part III/IV detail columns:
1056        "donee_ein",
1057        "donee_address",
1058        "appraiser_tin",
1059        "appraiser_ptin",
1060        "appraiser_qualifications",
1061        "appraisal_date",
1062    ])?;
1063    for row in form_8283(state, year, details) {
1064        let d = row.details.as_ref();
1065        w.write_record([
1066            row.section
1067                .map(form8283_section_tag)
1068                .unwrap_or("")
1069                .to_string(),
1070            row.description,
1071            form8283_how_acquired_tag(row.how_acquired).to_string(),
1072            row.date_acquired.to_string(),
1073            row.date_contributed.to_string(),
1074            row.cost_basis.to_string(),
1075            row.fmv.to_string(),
1076            row.claimed_deduction
1077                .map(|d| d.to_string())
1078                .unwrap_or_default(),
1079            row.fmv_method,
1080            row.donee,
1081            row.appraiser,
1082            row.needs_review.to_string(),
1083            // NEW:
1084            d.and_then(|d| d.donee_ein.clone()).unwrap_or_default(),
1085            d.and_then(|d| d.donee_address.clone()).unwrap_or_default(),
1086            d.and_then(|d| d.appraiser_tin.clone()).unwrap_or_default(),
1087            d.and_then(|d| d.appraiser_ptin.clone()).unwrap_or_default(),
1088            d.and_then(|d| d.appraiser_qualifications.clone())
1089                .unwrap_or_default(),
1090            d.and_then(|d| d.appraisal_date.map(|dt| dt.to_string()))
1091                .unwrap_or_default(),
1092        ])?;
1093    }
1094    w.flush()?;
1095    Ok(())
1096}
1097
1098/// P2-B Task 2: write `form8949.csv` — one row per `DisposalLeg` disposed in `year`. Stable
1099/// snake_case columns; exact `Decimal`/`i64` string values (NFR5). 0o600 via `open_owner_only`.
1100fn write_form8949_csv(
1101    out_dir: &Path,
1102    state: &LedgerState,
1103    year: i32,
1104) -> Result<(), crate::CliError> {
1105    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("form8949.csv"))?);
1106    w.write_record([
1107        "part",
1108        "box",
1109        "box_needs_review",
1110        "description",
1111        "date_acquired",
1112        "date_sold",
1113        "proceeds",
1114        "cost_basis",
1115        "adjustment_code",
1116        "adjustment_amount",
1117        "gain",
1118        "wallet",
1119        "disposition_kind",
1120    ])?;
1121    for r in form_8949(state, year) {
1122        w.write_record([
1123            form8949_part_tag(r.part).to_string(),
1124            form8949_box_tag(r.box_).to_string(),
1125            r.box_needs_review.to_string(),
1126            r.description,
1127            r.date_acquired.to_string(),
1128            r.date_sold.to_string(),
1129            r.proceeds.to_string(),
1130            r.cost_basis.to_string(),
1131            r.adjustment_code,
1132            r.adjustment_amount.to_string(),
1133            r.gain.to_string(),
1134            wallet_label(&r.wallet),
1135            dispose_kind_tag(r.disposition_kind).to_string(),
1136        ])?;
1137    }
1138    w.flush()?;
1139    Ok(())
1140}
1141
1142/// P2-B Task 3: write `schedule_d.csv` — the two RAW pre-netting part totals (Part I ST, Part II LT)
1143/// for `year`. §1222/§1211/§1212 netting + carryforward is applied by engine B, not here (D3).
1144fn write_schedule_d_csv(
1145    out_dir: &Path,
1146    state: &LedgerState,
1147    year: i32,
1148) -> Result<(), crate::CliError> {
1149    let mut w = Writer::from_writer(fsperms::open_owner_only(&out_dir.join("schedule_d.csv"))?);
1150    w.write_record(["part", "proceeds", "cost_basis", "gain"])?;
1151    let totals = schedule_d(state, year);
1152    for (part, p) in [("ST", &totals.st), ("LT", &totals.lt)] {
1153        w.write_record([
1154            part.to_string(),
1155            p.proceeds.to_string(),
1156            p.cost_basis.to_string(),
1157            p.gain.to_string(),
1158        ])?;
1159    }
1160    w.flush()?;
1161    Ok(())
1162}
1163
1164/// UX-P4-1: the pseudo-disclosure channel for a tax-year figure — which, if any, deliberately-synthetic
1165/// input the number rides on. Carries the FULL §3.1 predicate (`pseudo_active() OR PseudoPlaceholder`) so a
1166/// caller cannot thread a single disjunct and silently drop the other (SPEC r2-N3). The two active channels
1167/// are mutually exclusive by PRECEDENCE — `Synthetic` (a pseudo synthetic lot/FMV; `pseudo_active()`, i.e.
1168/// `pseudo_synthetic_count > 0`) is chosen ahead of `Placeholder` (computed on the all-$0 pseudo placeholder
1169/// profile; mode on, nothing stored, `count == 0`) — even though the underlying states can co-occur.
1170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1171pub enum PseudoDisclosure {
1172    /// Not pseudo-contributed — no banner, no suffix.
1173    None,
1174    /// A pseudo synthetic lot/FMV feeds the figure (`pseudo_active()`).
1175    Synthetic,
1176    /// Computed on the all-$0 pseudo placeholder profile (mode on, nothing stored, `count == 0`).
1177    Placeholder,
1178}
1179
1180impl PseudoDisclosure {
1181    /// True iff the figure is pseudo-contributed (either active channel).
1182    pub fn contributed(self) -> bool {
1183        self != PseudoDisclosure::None
1184    }
1185    /// The ` [PSEUDO]` suffix for a headline total line (leading space kept so a last-field scraper reads
1186    /// `[PSEUDO]` and fails loud), or `""` when not contributed.
1187    pub fn suffix(self) -> &'static str {
1188        if self.contributed() {
1189            " [PSEUDO]"
1190        } else {
1191            ""
1192        }
1193    }
1194    /// The channel-aware top banner (with a trailing newline), or `""` when not contributed. Each clause is
1195    /// true for its channel; the remedy pointers are live only for the channel that fires them (SPEC §3.1).
1196    pub fn banner(self) -> &'static str {
1197        match self {
1198            PseudoDisclosure::None => "",
1199            PseudoDisclosure::Synthetic => {
1200                "⚠ [PSEUDO] This vault has pseudo-reconciled (deliberately-synthetic) entries; figures shown \
1201                 are an ESTIMATE, not filing-ready. See '[PSEUDO]' rows in 'btctax report' and the \
1202                 [PseudoReconcileActive] advisory in 'btctax verify'; resolve them before filing.\n"
1203            }
1204            PseudoDisclosure::Placeholder => {
1205                "⚠ [PSEUDO] These figures are estimated on a synthetic $0 placeholder profile — no tax \
1206                 profile or full-return inputs are stored for this year. This is an ESTIMATE, not \
1207                 filing-ready. Set a tax profile ('btctax tax-profile --year <Y> …' — setting is the \
1208                 default; '--show' inverts), import inputs ('btctax income import'), or turn pseudo mode off \
1209                 ('btctax reconcile pseudo off').\n"
1210            }
1211        }
1212    }
1213}
1214
1215/// Task 9 (B.5) + Task 10 (M4): render the `TaxOutcome` for `report --tax-year <y>`. Exact Decimal
1216/// Display; no float (NFR5). B-M2 fold: surfaces the ordinary-rate attributable delta so the three
1217/// printed attributable components visibly reconcile to `total_federal_tax_attributable`.
1218///
1219/// `advisory` is the optional M4 carryforward-consistency warning string (Task 10). When `Some`,
1220/// it is printed as a non-gating advisory line that does not affect the exit code.
1221///
1222/// `pseudo` (UX-P4-1): the disclosure channel. When contributed, an unconditional top banner is emitted and
1223/// the TOTAL line is ` [PSEUDO]`-suffixed — so neither a human nor a single-line scraper reads the
1224/// authoritative number without the flag.
1225pub fn render_tax_outcome(
1226    year: i32,
1227    out: &btctax_core::TaxOutcome,
1228    advisory: Option<&str>,
1229    pseudo: PseudoDisclosure,
1230) -> String {
1231    use btctax_core::TaxOutcome::*;
1232    let mut s = String::new();
1233    s.push_str(pseudo.banner());
1234    let _ = writeln!(s, "Federal tax attributable to crypto — tax year {year}");
1235    match out {
1236        NotComputable(b) => {
1237            let _ = writeln!(s, "  NOT COMPUTABLE [{:?}]: {}", b.kind, b.detail);
1238        }
1239        Computed(r) => {
1240            let _ = writeln!(
1241                s,
1242                "  net short-term: {}   net long-term: {}",
1243                fmt_money(r.st_net),
1244                fmt_money(r.lt_net)
1245            );
1246            let _ = writeln!(
1247                s,
1248                "  crypto ordinary income (level): {}",
1249                fmt_money(r.ordinary_from_crypto)
1250            );
1251            // B-M2: surface the ordinary-rate attributable DELTA so the three attributable components
1252            // visibly reconcile to TOTAL. By the pinned identity this equals (ord_with − ord_without) exactly.
1253            let ordinary_rate_attributable = r.total_federal_tax_attributable - r.ltcg_tax - r.niit;
1254            let _ = writeln!(
1255                s,
1256                "  ordinary-rate tax (attributable): {}",
1257                fmt_money(ordinary_rate_attributable)
1258            );
1259            let _ = writeln!(
1260                s,
1261                "  LTCG tax (attributable): {}   NIIT (attributable): {}",
1262                fmt_money(r.ltcg_tax),
1263                fmt_money(r.niit)
1264            );
1265            let _ = writeln!(
1266                s,
1267                "  TOTAL federal tax attributable to crypto (delta): {}{}   \
1268                (= ordinary-rate + LTCG + NIIT attributable)",
1269                fmt_money(r.total_federal_tax_attributable),
1270                pseudo.suffix()
1271            );
1272            let _ = writeln!(
1273                s,
1274                "  §1211 loss deduction (level): {}   carryforward out: short {} / long {}",
1275                fmt_money(r.loss_deduction),
1276                fmt_money(r.carryforward_out.short),
1277                fmt_money(r.carryforward_out.long)
1278            );
1279            let _ = writeln!(
1280                s,
1281                "  marginal rates: ordinary {} / LTCG {} / NIIT increased by crypto: {}",
1282                r.marginal_rates.ordinary,
1283                r.marginal_rates.ltcg,
1284                if r.marginal_rates.niit_applies {
1285                    "yes"
1286                } else {
1287                    "no"
1288                }
1289            );
1290            let _ = writeln!(
1291                s,
1292                "  (incremental ceteris-paribus delta on the minimal profile; \
1293                excludes AGI-driven SS/IRMAA/AMT/QBI/phaseout effects — I5. §1411 NIIT reduces NII by the \
1294                §1211(b)-allowed net capital loss (≤ $3,000 / $1,500 MFS — Form 8960 line 5a / §1.1411-4(d)) \
1295                and is floored at $0; crypto ordinary income (mining/staking/airdrops/rewards) is correctly \
1296                excluded from NII; crypto-lending interest income (§1411(c)(1)(A)(i)) is INCLUDED in NII; \
1297                mining/staking/airdrops/rewards remain excluded (SE income per §1411(c)(6) or non-NII other income).)"
1298            );
1299        }
1300    }
1301    // M4 (Task 10): non-gating advisory — render after the main block so it is visible
1302    // regardless of whether the outcome is Computed or NotComputable.
1303    if let Some(msg) = advisory {
1304        let _ = writeln!(s, "  ADVISORY (M4): {msg}");
1305    }
1306    s
1307}
1308
1309/// The house wrap width for advisory text (the widest line the tool prints anywhere).
1310pub(crate) const ADVISORY_WRAP_COLS: usize = 92;
1311
1312/// Wrap `text` under a `  • ` bullet, with continuation lines hanging under the bullet's TEXT (a
1313/// 4-space indent) rather than under the bullet glyph. Breaks on whitespace only; a word longer than
1314/// the line (a URL, say) is left to overflow rather than being cut mid-token — a broken citation is
1315/// worse than a long line.
1316pub(crate) fn wrap_bulleted(text: &str) -> String {
1317    const BULLET: &str = "  \u{2022} ";
1318    const HANG: &str = "    ";
1319    let mut out = String::new();
1320    let mut line = String::from(BULLET);
1321    let mut have_word = false;
1322
1323    for word in text.split_whitespace() {
1324        let prospective = line.chars().count() + usize::from(have_word) + word.chars().count();
1325        if have_word && prospective > ADVISORY_WRAP_COLS {
1326            out.push_str(line.trim_end());
1327            out.push('\n');
1328            line = String::from(HANG);
1329            have_word = false;
1330        }
1331        if have_word {
1332            line.push(' ');
1333        }
1334        line.push_str(word);
1335        have_word = true;
1336    }
1337    out.push_str(line.trim_end());
1338    out
1339}
1340
1341/// Render the Phase-5 full-return **advisories** (SPEC §3.4 / §9.2) — the loud, non-gating notes that a
1342/// favorable credit was omitted conservatively (your tax is OVERSTATED), or that a disclosure is yours to
1343/// make. Never changes a number and never changes the exit code.
1344pub fn render_advisories(advisories: &[btctax_core::tax::advisories::Advisory]) -> String {
1345    let mut s = String::new();
1346    if advisories.is_empty() {
1347        return s;
1348    }
1349    let _ = writeln!(s, "\n  ── ADVISORIES ({}) ──", advisories.len());
1350    for a in advisories {
1351        // Wrap each message under its bullet (`p5-n5`): an advisory is a 300–400-character sentence, and
1352        // an unwrapped one is unreadable in an 80-column terminal. The message text itself is
1353        // single-sourced in core — this only decides where the line breaks are.
1354        let _ = writeln!(s, "{}", wrap_bulleted(&a.message()));
1355    }
1356    let _ = writeln!(
1357        s,
1358        "  (Advisories never change a number and never fail the command. See `btctax limitations`.)"
1359    );
1360    s
1361}
1362
1363/// The §4.12 provenance label for the resolved profile — printed on the full-return output so a
1364/// reviewer can audit which source produced the figures (`p2-provenance-printing`).
1365pub fn provenance_label(p: crate::resolve::Provenance) -> &'static str {
1366    use crate::resolve::Provenance::*;
1367    match p {
1368        ReturnInputs => "ReturnInputs (derived from line items)",
1369        StoredProfile => "stored TaxProfile (raw override)",
1370        PseudoPlaceholder => "pseudo-reconcile placeholder ($0)",
1371        Missing => "none (TaxProfileMissing)",
1372    }
1373}
1374
1375/// Render the **§6 dual report**: the absolute filed-return liability (Form 1040, WITH crypto) and the
1376/// crypto-attribution DELTA are **different questions** — shown together, labeled, and NEVER reconciled to
1377/// the dollar (SPEC §6). Only produced for a `ReturnInputs`-provenance year (a full 1040 exists). `delta`
1378/// is the same `TaxOutcome` the crypto-delta block already showed above. Provenance is printed here (§4.12).
1379/// ★ The absolute block renders the **PRINTED** figures — the whole-dollar, cross-footing lines the filed
1380/// PDF carries — not the exact-cents computation behind them (ARCH-P6 Q3).
1381///
1382/// The clinching case is line 37. "Amount you owe" is not an analytical figure; it is an instruction to
1383/// write a check. A tool that says $12,345.67 in the terminal and prints $12,347 on the filed form has
1384/// produced TWO authoritative answers to "what do I pay", and no LIMITATIONS paragraph repairs that. The
1385/// moment a report line is labelled with a form-line citation, it has promised the FORM's figure.
1386///
1387/// The crypto-DELTA block below stays in exact cents: it is not a filed figure — it answers a different
1388/// question (§6), and the frozen engine computes it in cents.
1389pub fn render_dual_report(
1390    year: i32,
1391    ar: &btctax_core::AbsoluteReturn,
1392    printed: &btctax_core::tax::packet::PrintedForms,
1393    delta: &btctax_core::TaxOutcome,
1394    provenance: crate::resolve::Provenance,
1395    pseudo: PseudoDisclosure,
1396) -> String {
1397    let f = &printed.f1040;
1398    let mut s = String::new();
1399    let _ = writeln!(
1400        s,
1401        "\n═══ Absolute filed return (Form 1040) — tax year {year} ═══"
1402    );
1403    let _ = writeln!(s, "  Profile source: {}", provenance_label(provenance));
1404    let _ = writeln!(s, "  Total income (1040 L9):   {}", fmt_money(f.line9));
1405    let _ = writeln!(s, "  Adjustments (L10):        {}", fmt_money(f.line10));
1406    let _ = writeln!(s, "  AGI (L11):                {}", fmt_money(f.line11));
1407    let ded_kind = if ar.deduction_is_itemized {
1408        "itemized"
1409    } else {
1410        "standard"
1411    };
1412    let _ = writeln!(s, "  Deduction (L12, {ded_kind}): {}", fmt_money(f.line12));
1413    if ar.qbi_deduction > Usd::ZERO {
1414        let _ = writeln!(s, "  QBI deduction (L13):      {}", fmt_money(f.line13));
1415    }
1416    let _ = writeln!(s, "  Taxable income (L15):     {}", fmt_money(f.line15));
1417    let _ = writeln!(s, "  Tax (L16):                {}", fmt_money(f.line16));
1418    if ar.foreign_tax_credit > Usd::ZERO {
1419        let _ = writeln!(
1420            s,
1421            "  Foreign tax credit (Sch 3 L1): {}",
1422            fmt_money(printed.sch_3.map_or(Usd::ZERO, |s3| s3.line1))
1423        );
1424    }
1425    if ar.se_tax_sch2_l4 > Usd::ZERO {
1426        let _ = writeln!(
1427            s,
1428            "  Self-employment tax (Sch 2 L4): {}",
1429            fmt_money(printed.sch_2.map_or(Usd::ZERO, |s2| s2.line4))
1430        );
1431    }
1432    if ar.additional_medicare.additional_medicare_tax > Usd::ZERO {
1433        let _ = writeln!(
1434            s,
1435            "  Additional Medicare (Form 8959 → Sch 2 L11): {}",
1436            fmt_money(printed.f8959.line18)
1437        );
1438    }
1439    if ar.niit.tax > Usd::ZERO {
1440        let _ = writeln!(
1441            s,
1442            "  Net Investment Income Tax (Form 8960 → Sch 2 L12): {}",
1443            fmt_money(printed.f8960.map_or(Usd::ZERO, |f| f.line17))
1444        );
1445    }
1446    let _ = writeln!(
1447        s,
1448        "  TOTAL TAX (L24):          {}{}",
1449        fmt_money(f.line24),
1450        pseudo.suffix()
1451    );
1452    let _ = writeln!(s, "  Total payments (L33):     {}", fmt_money(f.line33));
1453    if f.line34 > Usd::ZERO {
1454        let _ = writeln!(s, "  → REFUND (L35a):          {}", fmt_money(f.line34));
1455    } else {
1456        let _ = writeln!(s, "  → AMOUNT OWED (L37):      {}", fmt_money(f.line37));
1457    }
1458    // §6: the two figures answer different questions and are NEVER reconciled.
1459    let delta_str = match delta {
1460        btctax_core::TaxOutcome::Computed(r) => fmt_money(r.total_federal_tax_attributable),
1461        btctax_core::TaxOutcome::NotComputable(_) => "not computable".to_string(),
1462    };
1463    let _ = writeln!(
1464        s,
1465        "\n  ── Two DIFFERENT questions — NOT reconciled (SPEC §6) ──"
1466    );
1467    let _ = writeln!(
1468        s,
1469        "  • Absolute TOTAL TAX (this filed return, WITH crypto): {}{}",
1470        fmt_money(f.line24),
1471        pseudo.suffix()
1472    );
1473    let _ = writeln!(
1474        s,
1475        "  • Crypto-attributable tax (DELTA, shown above):        {delta_str}"
1476    );
1477    let _ = writeln!(
1478        s,
1479        "  The delta's implied deduction is fixed at derivation time (non-crypto AGI), so it is \
1480         APPROXIMATE where a\n  deduction is AGI-sensitive (e.g. the 7.5% medical floor); the two do NOT \
1481         reconcile to the dollar."
1482    );
1483    s
1484}
1485
1486/// P2-B Task 3: render the RAW pre-netting Schedule D part totals (Part I ST, Part II LT) for
1487/// `year`, mirroring `render_tax_outcome`. These are the Form 8949/Schedule D part totals BEFORE
1488/// §1222/§1211/§1212 netting + carryforward — that netting is applied in the tax computation
1489/// (`report --tax-year`), and the netted figures are shown by `render_tax_outcome` above.
1490///
1491/// When `outcome` is `Computed`, the standard netting note is shown. When `outcome` is
1492/// `NotComputable`, a caveat is printed instead: the raw totals are valid disposal sums but are
1493/// informational — no netting or carryforward is applied because the tax is not computable.
1494/// The raw totals are ALWAYS shown (never suppressed); only the trailing note differs.
1495pub fn render_schedule_d(
1496    year: i32,
1497    totals: &ScheduleDTotals,
1498    outcome: &btctax_core::TaxOutcome,
1499) -> String {
1500    let mut s = String::new();
1501    let _ = writeln!(
1502        s,
1503        "Schedule D (raw pre-netting part totals) — tax year {year}"
1504    );
1505    let _ = writeln!(
1506        s,
1507        "  Part I  (short-term): proceeds {}   cost basis {}   gain {}",
1508        fmt_money(totals.st.proceeds),
1509        fmt_money(totals.st.cost_basis),
1510        fmt_money(totals.st.gain)
1511    );
1512    let _ = writeln!(
1513        s,
1514        "  Part II (long-term):  proceeds {}   cost basis {}   gain {}",
1515        fmt_money(totals.lt.proceeds),
1516        fmt_money(totals.lt.cost_basis),
1517        fmt_money(totals.lt.gain)
1518    );
1519    match outcome {
1520        btctax_core::TaxOutcome::NotComputable(_) => {
1521            let _ = writeln!(
1522                s,
1523                "  (raw disposition totals shown above; the year's tax is NOT COMPUTABLE until \
1524                 the blocker is resolved — these Form 8949/Schedule D part totals are \
1525                 informational and are not netted/carried until the tax computes)."
1526            );
1527        }
1528        btctax_core::TaxOutcome::Computed(_) => {
1529            let _ = writeln!(
1530                s,
1531                "  Note: §1222/§1211/§1212 netting + carryforward are applied in the tax \
1532                 computation (report --tax-year); these are the raw pre-netting Form \
1533                 8949/Schedule D part totals."
1534            );
1535        }
1536    }
1537    s
1538}
1539
1540/// P2-D Task 2 / Chunk B (Schedule SE): render the standalone §1401 SE-tax block for `year` as an
1541/// informational block that does NOT feed engine B (`TaxResult::total_federal_tax_attributable` is
1542/// UNCHANGED by SE tax).
1543///
1544/// Three-way `None` split [R0-I1] (no silent drop — mirrors P2-C's m6):
1545/// - `gross_se == 0` → `None` (no business SE income → no Schedule SE section at all).
1546/// - `gross_se > 0 && !table_present` → a "SS wage base unavailable for {year}" note (business SE
1547///   income exists but the year has no bundled table → the wage base is unknown; the §1401 tax is
1548///   NOT computed rather than silently dropped).
1549/// - `gross_se > 0 && table_present && result == None` → a "fully expensed" line (expenses ≥ gross
1550///   → net_se == 0 → no §1401 SE tax owed; distinct from the "wage base unavailable" case).
1551/// - `result = Some(r)` → the full Schedule SE section (breakout or $0 note, components, total,
1552///   §164(f) advisory, W-2 coordination, the Chunk-B expense advisory, and the [D5] standalone note).
1553///
1554/// # Parameters
1555/// - `gross_se`: `se_net_income(state, year)` — the GROSS SE income before expenses (caller computes).
1556/// - `table_present`: `tables.table_for(year).is_some()` (caller has this from the `and_then` chain).
1557/// - `schedule_c_expenses`: from `TaxProfile.schedule_c_expenses` (≥ 0). When > 0 triggers the
1558///   breakout line and the Chunk-B ordinary-income advisory.
1559/// - `w2_ss_wages` / `w2_medicare_wages`: from `TaxProfile` (both ≥ 0). When either is > $0 the
1560///   W-2 coordinated disclosure is rendered; when both are $0 the short $0-assumed note is shown.
1561pub fn render_schedule_se(
1562    year: i32,
1563    result: Option<&SeTaxResult>,
1564    gross_se: Usd,
1565    table_present: bool,
1566    schedule_c_expenses: Usd,
1567    w2_ss_wages: Usd,
1568    w2_medicare_wages: Usd,
1569) -> Option<String> {
1570    match result {
1571        Some(r) => {
1572            let mut s = String::new();
1573            let _ = writeln!(
1574                s,
1575                "Schedule SE (§1401 self-employment tax on business crypto income) — tax year {year}"
1576            );
1577            // [Chunk B] Breakout line or $0 note depending on whether expenses were supplied.
1578            if schedule_c_expenses > Usd::ZERO {
1579                // The gross for display = net_se + expenses (since net_se = max(0, gross − expenses)
1580                // and net_se > 0 here, gross = net_se + expenses exactly).
1581                let gross_display = r.net_se + schedule_c_expenses;
1582                let _ = writeln!(
1583                    s,
1584                    "  gross business income {} \u{2212} Schedule C expenses {} = net SE earnings {}",
1585                    fmt_money(gross_display),
1586                    fmt_money(schedule_c_expenses),
1587                    fmt_money(r.net_se)
1588                );
1589                // [Chunk B / I3-mechanism] Ordinary-income advisory — correct mechanism; NO OTI-edit prescription.
1590                let _ = writeln!(
1591                    s,
1592                    "  (Schedule C advisory) Schedule C expenses also reduce your ORDINARY taxable \
1593                     income, but the income-tax total above uses GROSS crypto income \u{2014} to first \
1594                     order it OVERSTATES your tax by your marginal ordinary rate applied to {}. The tax \
1595                     profile cannot express this (an `ordinary_taxable_income` edit would shift both \
1596                     legs of the crypto-attributable delta); the engine-side coordination is deferred \
1597                     \u{2014} coordinate it on your actual return.",
1598                    fmt_money(schedule_c_expenses)
1599                );
1600            } else {
1601                let _ = writeln!(
1602                    s,
1603                    "  net self-employment income (business crypto, Interest excluded): {}",
1604                    fmt_money(r.net_se)
1605                );
1606                let _ = writeln!(
1607                    s,
1608                    "  (Schedule C) no Schedule C expenses supplied (--schedule-c-expenses)"
1609                );
1610            }
1611            let _ = writeln!(
1612                s,
1613                "  \u{00d7} 92.35% net-earnings factor (\u{00a7}1402(a)) = net SE earnings: {}",
1614                fmt_money(r.base)
1615            );
1616            let _ = writeln!(
1617                s,
1618                "  Social Security component (12.4%, §1401(a); capped at the SS wage base): {}",
1619                fmt_money(r.ss)
1620            );
1621            let _ = writeln!(
1622                s,
1623                "  Medicare component (2.9%, §1401(b); uncapped): {}",
1624                fmt_money(r.medicare)
1625            );
1626            let _ = writeln!(
1627                s,
1628                "  Additional Medicare component (0.9%, §1401(b)(2)): {}",
1629                fmt_money(r.addl)
1630            );
1631            let _ = writeln!(
1632                s,
1633                "  TOTAL self-employment tax (§1401): {}",
1634                fmt_money(r.total)
1635            );
1636            let _ = writeln!(
1637                s,
1638                "  §164(f) one-half-SE-tax deduction (above-the-line; EXCLUDES Additional Medicare per \
1639                 §164(f)(1)): {}",
1640                fmt_money(r.deductible_half)
1641            );
1642            // [Chunk A / R0-I3] §164(f) advisory — quantified first-order overstatement; NO prescription
1643            // to edit ordinary_taxable_income (wrong mechanism — see spec D3/R0-I3 rationale).
1644            let _ = writeln!(
1645                s,
1646                "  (§164(f) advisory) The §164(f) deduction ({}) is NOT auto-coordinated into the \
1647                 income-tax total above — to first order, that total overstates your combined tax by \
1648                 your marginal ordinary rate applied to {}. The tax profile cannot express this deduction \
1649                 directly (reducing `ordinary_taxable_income` would shift BOTH legs of the \
1650                 crypto-attributable delta and only correct the bracket differential, not the level) — \
1651                 coordinate it on your actual return.",
1652                fmt_money(r.deductible_half),
1653                fmt_money(r.deductible_half)
1654            );
1655            // [Chunk A / D3] W-2 coordination disclosure — accurate when W-2 values are set;
1656            // short $0-assumed note otherwise. REMOVES the old OVERSTATED/UNDERSTATED hedging.
1657            if w2_ss_wages > Usd::ZERO || w2_medicare_wages > Usd::ZERO {
1658                let _ = writeln!(
1659                    s,
1660                    "  (W-2 coordination applied) SS cap = max(0, wage base \u{2212} {}) (Box 3+7); \
1661                     Additional-Medicare threshold reduced (not below 0) by {} (Box 5, \
1662                     §1401(b)(2)(B)/Form 8959 Part II).",
1663                    fmt_money(w2_ss_wages),
1664                    fmt_money(w2_medicare_wages)
1665                );
1666            } else {
1667                let _ = writeln!(
1668                    s,
1669                    "  (W-2) assumes $0 W-2 wages (set --w2-ss-wages/--w2-medicare-wages on the tax \
1670                     profile if you had a wage job)."
1671                );
1672            }
1673            // [burndown-3 D2] §6017 $400 filing floor — the test is on the ×0.9235 base (§1402(a),
1674            // which includes the §1402(a)(12) 7.65% reduction), NOT the pre-factor net_se.
1675            if r.base < rust_decimal::Decimal::from(400) {
1676                let _ = writeln!(
1677                    s,
1678                    "  (§6017 filing floor) Net earnings from self-employment ({base}) are below $400: \
1679                     a Schedule SE filing is required on account of this income only when net earnings \
1680                     from self-employment (the ×92.35% base, §1402(a)) are $400 or more (§6017), and \
1681                     below that floor no §1401 SE tax is imposed (§1402(b)(2); church employee income \
1682                     excepted — §1402(j)(2), not modeled) — the figures above are shown for \
1683                     transparency (other self-employment activities, if any, combine on your actual \
1684                     Schedule SE).",
1685                    base = fmt_money(r.base)
1686                );
1687            }
1688            // [D5] standalone note — SE tax is a SEPARATE liability, not in the income-tax + NIIT total.
1689            let _ = writeln!(
1690                s,
1691                "  (standalone) This §1401 SE tax is a SEPARATE federal liability, NOT included in the \
1692                 income-tax + NIIT total above; the §164(f) one-half-SE-tax deduction is not \
1693                 auto-coordinated into that total."
1694            );
1695            Some(s)
1696        }
1697        None => {
1698            if gross_se.is_zero() {
1699                None // no business SE income → no Schedule SE section
1700            } else if !table_present {
1701                // Business SE income present but no bundled table → wage base unknown; do NOT drop.
1702                let mut s = String::new();
1703                let _ = writeln!(
1704                    s,
1705                    "Schedule SE (§1401 self-employment tax) — tax year {year}"
1706                );
1707                let _ = writeln!(
1708                    s,
1709                    "  SS wage base unavailable for {year}: business self-employment income is present \
1710                     but no bundled tax table (ss_wage_base) exists for {year}; the §1401 SE tax was \
1711                     NOT computed (no silent drop)."
1712                );
1713                Some(s)
1714            } else {
1715                // Business SE income present + table available + net_se == 0: fully expensed.
1716                // [R0-I1] The liability status is "no tax owed", NOT "couldn't compute".
1717                let mut s = String::new();
1718                let _ = writeln!(
1719                    s,
1720                    "Schedule SE (§1401 self-employment tax on business crypto income) — tax year {year}"
1721                );
1722                let _ = writeln!(
1723                    s,
1724                    "  fully expensed: gross {} \u{2212} Schedule C expenses {} \u{2264} $0 \
1725                     \u{2192} no \u{00a7}1401 SE tax for {year}.",
1726                    fmt_money(gross_se),
1727                    fmt_money(schedule_c_expenses)
1728                );
1729                Some(s)
1730            }
1731        }
1732    }
1733}
1734
1735/// P2-C Task 3 (D3): Form 709 gift **per-donee advisory** (§2503(b) annual exclusion applied
1736/// independently per donee, not in aggregate).
1737///
1738/// Groups `Removal{Gift}` legs by their `donee` label for `year`:
1739/// - **`None`** when there are NO Gift removals in the year (even with a table present). [R0-I2]
1740/// - **`Some(note)` [R0-m6]** when gifts ARE present but the year has NO bundled table (exclusion
1741///   unavailable): Form 709 exposure is NOT evaluated — do NOT silently return `None`.
1742/// - **`Some(advisory)`** for all other cases: per-labeled-donee §2503(b) breakdown (each donee's
1743///   total vs the per-donee exclusion; filing trigger fires when ANY labeled donee exceeds the
1744///   exclusion), plus an unlabeled-bucket caveat when any `None`-donee gifts exist.
1745///
1746/// **Why per-donee matters (§2503(b)):** the exclusion applies to each recipient independently.
1747/// Two donees at $15k each with a $19k exclusion → $0 taxable (the old aggregate was WRONG: it
1748/// would flag the $30k combined total, even though neither donee exceeded their exclusion).
1749///
1750/// **Unlabeled bucket:** `None`-donee gifts cannot have per-donee exclusion applied; a conservative
1751/// aggregate-vs-one-exclusion signal is emitted with an explicit caveat. Nothing is silently dropped.
1752///
1753/// **Donations excluded:** `Removal{Donation}` (§170) must NOT appear here — this advisory is for
1754/// §2503(b) Gifts only. `kind == Gift` filter enforces this.
1755///
1756/// Standalone informational artifact — does NOT feed `compute_tax_year` / engine B.
1757pub fn render_gift_advisory(
1758    state: &LedgerState,
1759    year: i32,
1760    prior_taxable_gifts: btctax_core::conventions::Usd,
1761    tables: &impl btctax_core::TaxTables,
1762) -> Option<String> {
1763    use std::collections::BTreeMap;
1764
1765    // [R0-I2] Preserve safety: any_gift guard — Donation removals do NOT count here.
1766    let any_gift = state
1767        .removals
1768        .iter()
1769        .any(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year);
1770    if !any_gift {
1771        return None; // (a) no Gift removals in the year
1772    }
1773
1774    // [R0-m6] gifts present but no bundled table → emit the note, never None.
1775    let t = match tables.table_for(year) {
1776        None => {
1777            let total: btctax_core::conventions::Usd = state
1778                .removals
1779                .iter()
1780                .filter(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year)
1781                .flat_map(|r| r.legs.iter())
1782                .map(|leg| leg.fmv_at_transfer)
1783                .sum();
1784            return Some(format!(
1785                "Form 709 gift advisory ({year}): gift annual-exclusion table unavailable for \
1786                 {year}; Form 709 exposure not evaluated — ${} in gifts recorded.",
1787                fmt_money(total)
1788            ));
1789        }
1790        Some(t) => t,
1791    };
1792    let excl = t.gift_annual_exclusion;
1793
1794    // Group Gift removals by donee label (BTreeMap → deterministic order; None → unlabeled bucket).
1795    let mut labeled: BTreeMap<String, btctax_core::conventions::Usd> = BTreeMap::new();
1796    let mut unlabeled_count: usize = 0;
1797    let mut unlabeled_total: btctax_core::conventions::Usd = Default::default();
1798
1799    for r in state
1800        .removals
1801        .iter()
1802        .filter(|r| r.kind == RemovalKind::Gift && r.removed_at.year() == year)
1803    {
1804        let fmv: btctax_core::conventions::Usd = r.legs.iter().map(|l| l.fmv_at_transfer).sum();
1805        match &r.donee {
1806            Some(label) => {
1807                *labeled.entry(label.clone()).or_default() += fmv;
1808            }
1809            None => {
1810                unlabeled_count += 1;
1811                unlabeled_total += fmv;
1812            }
1813        }
1814    }
1815
1816    // Per-donee §2503(b) analysis.
1817    let mut filing_required_donees: Vec<String> = Vec::new();
1818    let mut total_taxable: btctax_core::conventions::Usd = Default::default();
1819    let mut s = format!("Form 709 gift advisory ({year}):");
1820
1821    if !labeled.is_empty() {
1822        s.push_str(&format!(
1823            "\n§2503(b) per-donee annual exclusion analysis (TY{year}, exclusion ${}):",
1824            fmt_money(excl)
1825        ));
1826        for (donee, &total) in &labeled {
1827            let applied = if total < excl { total } else { excl };
1828            let taxable: btctax_core::conventions::Usd = if total > excl {
1829                total - excl
1830            } else {
1831                Default::default()
1832            };
1833            s.push_str(&format!(
1834                "\n  {donee}: total ${}, exclusion applied ${}, taxable ${}",
1835                fmt_money(total),
1836                fmt_money(applied),
1837                fmt_money(taxable)
1838            ));
1839            if total > excl {
1840                filing_required_donees.push(donee.clone());
1841                total_taxable += taxable;
1842            }
1843        }
1844        if !filing_required_donees.is_empty() {
1845            s.push_str(&format!(
1846                "\nForm 709 filing required (donee(s): {}). Total taxable gifts: ${}.",
1847                filing_required_donees.join(", "),
1848                fmt_money(total_taxable)
1849            ));
1850        } else {
1851            s.push_str(&format!(
1852                "\nNo Form 709 filing required based on per-donee totals \
1853                 (each ≤ ${} exclusion). Total taxable gifts: $0.00.",
1854                fmt_money(excl)
1855            ));
1856        }
1857    }
1858
1859    if unlabeled_count > 0 {
1860        s.push_str(&format!(
1861            "\nNOTE: {unlabeled_count} gift(s) totalling ${} have no donee label — the §2503(b) \
1862             annual exclusion is PER DONEE and cannot be applied without one; label them via \
1863             `reconcile reclassify-outflow --donee`. Shown as a single conservative aggregate.",
1864            fmt_money(unlabeled_total)
1865        ));
1866        // Conservative aggregate signal (old per-bucket logic): keep the signal so nothing is
1867        // silently dropped; mark it explicitly as a conservative estimate (may span multiple donees).
1868        if unlabeled_total > excl {
1869            s.push_str(&format!(
1870                "\n  Conservative aggregate ${} > ${} (one exclusion); \
1871                 verify per-donee totals after labelling.",
1872                fmt_money(unlabeled_total),
1873                fmt_money(excl)
1874            ));
1875        } else {
1876            s.push_str(&format!(
1877                "\n  Conservative aggregate ${} \u{2264} ${} (one exclusion); \
1878                 per-donee exposure unverifiable without labels.",
1879                fmt_money(unlabeled_total),
1880                fmt_money(excl)
1881            ));
1882        }
1883    }
1884
1885    // [D3 / R0-I1] §2505 lifetime (basic) exclusion consumption block.
1886    // current_year_taxable = total_taxable (Σ LABELED-donee taxable, per Chunk-2 design).
1887    // unlabeled gifts are excluded from this figure (their per-donee taxable is unknown).
1888    let lifetime_excl = t.gift_lifetime_exclusion;
1889    let cumulative_taxable = prior_taxable_gifts + total_taxable;
1890
1891    // Emit block only when cumulative > 0 (covers prior-only [M4] and over-annual cases).
1892    if cumulative_taxable > btctax_core::conventions::Usd::ZERO {
1893        let remaining = if cumulative_taxable >= lifetime_excl {
1894            btctax_core::conventions::Usd::ZERO
1895        } else {
1896            lifetime_excl - cumulative_taxable
1897        };
1898        s.push_str(&format!(
1899            "\n§2505 lifetime (basic) exclusion: you have used ${} of your ${} ({year}) lifetime \
1900             exclusion (${} remaining). No gift tax is DUE until cumulative taxable gifts exceed \
1901             the lifetime exclusion.",
1902            fmt_money(cumulative_taxable),
1903            fmt_money(lifetime_excl),
1904            fmt_money(remaining),
1905        ));
1906        // Strict `>`: at exactly the exclusion → remaining $0, NOT exceeded.
1907        if cumulative_taxable > lifetime_excl {
1908            let excess = cumulative_taxable - lifetime_excl;
1909            s.push_str(&format!(
1910                "\nlifetime exclusion EXCEEDED — gift tax may be due on ${} \
1911                 (the excess base past the unified credit, not a computed tax); \
1912                 consult a professional.",
1913                fmt_money(excess),
1914            ));
1915        }
1916        // [R0-I2] Unlabeled-omission disclosure: when unlabeled gifts exist, §2505 consumption
1917        // is understated (unlabeled gifts could have taxable amounts not reflected here).
1918        if unlabeled_count > 0 {
1919            s.push_str(&format!(
1920                "\n§2505 consumption reflects LABELED-donee taxable gifts only; \
1921                 {unlabeled_count} unlabeled gift(s) totalling ${} are NOT included — \
1922                 label them via `--donee` for a complete figure; consumption may be \
1923                 understated / remaining overstated.",
1924                fmt_money(unlabeled_total),
1925            ));
1926        }
1927    }
1928
1929    // [R0-I1] Updated caveats: stale "§2505 … later chunk (Chunk 3)" removed; §2513 and
1930    // future-interest caveats preserved; §2505-specific caveats added.
1931    s.push_str(
1932        "\nCaveats: §2513 gift-splitting (MFJ) not modeled (single-filer advisory only); \
1933         future-interest gifts (which require Form 709 filing regardless of amount) not \
1934         detectable; §2505 figures are advisory only — no portability/DSUE (§2010(c)(4)) \
1935         applied; prior cumulative taxable gifts are user-supplied (default $0 if \
1936         --prior-taxable-gifts not given).",
1937    );
1938
1939    Some(s)
1940}
1941
1942// ── Sub-project C: optimize run ─────────────────────────────────────────────────────────────────
1943
1944/// Format a lot-pick slice as comma-separated `"<event>#<split>:<sat>"` entries for proposal display.
1945/// Mirrors the grammar `eventref::parse_lot_pick` accepts, so picks are both human-readable and
1946/// round-trip-parseable. An empty pick list renders as `"(none)"`.
1947fn picks_str(picks: &[btctax_core::LotPick]) -> String {
1948    if picks.is_empty() {
1949        return "(none)".to_string();
1950    }
1951    picks
1952        .iter()
1953        .map(|p| {
1954            format!(
1955                "{}#{}:{}",
1956                p.lot.origin_event_id.canonical(),
1957                p.lot.split_sequence,
1958                p.sat
1959            )
1960        })
1961        .collect::<Vec<_>>()
1962        .join(", ")
1963}
1964
1965/// Render a `OptimizeProposal` (Mode-1 what-if) for the `optimize run` command. Returns a String
1966/// containing the proposal header, any approximate banner, the aggregate tax delta, per-disposal
1967/// rows (with proposed selection + compliance status + persistability), and the R0-M2 caveat footer.
1968///
1969/// **Approximate banner (R0-C1/C3/R2-C1):** when `p.approximate == true`, a ⚠ APPROXIMATE banner
1970/// and the specific `approx_reason` are printed. When `false`, no banner is printed (proven global
1971/// minimum — do NOT add a banner for this case).
1972///
1973/// **R2-M1 no-change rows:** a disposal whose `proposed_selection == current_selection` has nothing
1974/// to attest or persist (the optimizer is NOT asking to change it). The persistability line is
1975/// suppressed and a "no change — already optimal" note is shown instead, preventing a misleading
1976/// "needs --attest" prompt on a row the user does not need to act on.
1977pub fn render_optimize_proposal(p: &btctax_core::OptimizeProposal) -> String {
1978    use btctax_core::{ApproxReason, Persistability};
1979    let mut s = String::new();
1980    let _ = writeln!(
1981        s,
1982        "Optimize (what-if) — tax year {} — NOTHING is filed or bound by running this.",
1983        p.year
1984    );
1985    // R0-C1/C3: a non-fully-enumerated result is NEVER presented as "the optimum" without this banner.
1986    if p.approximate {
1987        let why = match p.approx_reason {
1988            Some(ApproxReason::ComboCapExceeded { combos, cap }) => format!(
1989                "input exceeded the exhaustive bound ({combos} combos > {cap}); \
1990                 a coordinate-descent fallback ran"
1991            ),
1992            Some(ApproxReason::ContentionUnenumerated { contended, .. }) => format!(
1993                "{contended} contended same-wallet disposal(s) could not be fully joint-enumerated"
1994            ),
1995            Some(ApproxReason::PoolHeuristic { lots, bound }) => format!(
1996                "a pool of {lots} lots exceeds the {bound}-lot exhaustive-enumeration bound; \
1997                 only a deterministic heuristic SUBSET of that pool's identifications was searched"
1998            ),
1999            None => "approximate".to_string(),
2000        };
2001        let _ = writeln!(
2002            s,
2003            "  \u{26a0} APPROXIMATE \u{2014} NOT a guaranteed global minimum: {why}."
2004        );
2005        let _ = writeln!(
2006            s,
2007            "    The true least-tax assignment may be lower; this is a disclosed improvement over your"
2008        );
2009        let _ = writeln!(
2010            s,
2011            "    current filing position (delta \u{2264} 0), NOT \u{2018}the least tax.\u{2019}"
2012        );
2013    }
2014    let _ = writeln!(
2015        s,
2016        "  current federal tax (attributable): {}",
2017        p.baseline_tax
2018    );
2019    let _ = writeln!(
2020        s,
2021        "  optimized federal tax (attributable): {}",
2022        p.optimized_tax
2023    );
2024    let _ = writeln!(
2025        s,
2026        "  delta (optimized \u{2212} current): {}  (negative = saving; always \u{2264} 0)",
2027        p.delta
2028    );
2029    for d in &p.per_disposal {
2030        let _ = writeln!(
2031            s,
2032            "  {} @ {} [{}] :: {}",
2033            d.disposal.canonical(),
2034            d.date,
2035            wallet_label(&d.wallet),
2036            compliance_status_tag(&d.status)
2037        );
2038        // R2-M1: a NO-CHANGE row (proposed == current) has nothing to attest/persist — `accept` SKIPS it
2039        // ("already optimal under current identification"). Do NOT print a persistability line here: a
2040        // `NeedsAttestation` "needs --attest" line on a disposal the optimizer is NOT asking to change is
2041        // misleading and invites a pointless/contradictory attestation. Show a no-change note instead.
2042        if d.proposed_selection == d.current_selection {
2043            let _ = writeln!(
2044                s,
2045                "      proposed: {}  [no change \u{2014} already optimal under current identification]",
2046                picks_str(&d.proposed_selection)
2047            );
2048            continue;
2049        }
2050        let persist = match d.persistable {
2051            Persistability::ContemporaneousNow => {
2052                "persistable now (made \u{2264} sale \u{2192} Contemporaneous)"
2053            }
2054            Persistability::NeedsAttestation => {
2055                "already executed \u{2014} needs `optimize accept --disposal <ref> \
2056                 --attest \"\u{2026}\"` (genuine contemporaneous ID only)"
2057            }
2058            Persistability::ForbiddenBroker2027 => {
2059                "2027+ broker-held \u{2014} CANNOT be persisted (own-books insufficient); \
2060                 FIFO is the defensible position"
2061            }
2062        };
2063        let _ = writeln!(
2064            s,
2065            "      proposed: {}  [{}]",
2066            picks_str(&d.proposed_selection),
2067            persist
2068        );
2069    }
2070    // R0-M2: surface the vertex-granularity limitation in OUTPUT, not only in docs.
2071    let _ = writeln!(
2072        s,
2073        "  (vertex-granularity identification: a multi-partial split landing exactly on a \
2074         tax-bracket kink is out of scope.)"
2075    );
2076    let _ = writeln!(
2077        s,
2078        "  (this is the tax IF you had identified thus; adequate ID must exist by the time \
2079         of sale \u{2014} \u{a7}1.1012-1(j))"
2080    );
2081    // C-M3: document the optimizer scope boundary (mirrors R0-M2 vertex-granularity caveat).
2082    let _ = writeln!(
2083        s,
2084        "  (scope: global over taxable-disposal lot selections; self-transfer lot routing is \
2085         held at its baseline position and is not re-optimized.)"
2086    );
2087    s
2088}
2089
2090/// Render an `AcceptOutcome` (Task 10 `optimize accept`): one line per persisted `LotSelection`
2091/// (with the appended decision id to pass to `reconcile void` for revocation, and the §A.5 basis
2092/// label) and one line per skipped disposal (with the gate reason). A persisted attestation is noted
2093/// inline on the `AttestedRecording` rows.
2094pub fn render_accept_outcome(o: &crate::cmd::optimize::AcceptOutcome) -> String {
2095    let mut s = String::new();
2096    let _ = writeln!(
2097        s,
2098        "Optimize accept \u{2014} {} persisted, {} skipped.",
2099        o.persisted.len(),
2100        o.skipped.len()
2101    );
2102    for (disposal, decision, basis) in &o.persisted {
2103        let _ = writeln!(
2104            s,
2105            "  PERSISTED {} \u{2192} LotSelection {} [{}]{}",
2106            disposal.canonical(),
2107            decision.canonical(),
2108            basis,
2109            if *basis == "AttestedRecording" {
2110                " (+ attestation recorded; revoke with `reconcile void`)"
2111            } else {
2112                " (revoke with `reconcile void`)"
2113            }
2114        );
2115    }
2116    for (disposal, reason) in &o.skipped {
2117        let _ = writeln!(s, "  skipped {}: {}", disposal.canonical(), reason);
2118    }
2119    if o.persisted.is_empty() && o.skipped.is_empty() {
2120        let _ = writeln!(s, "  (no disposals matched)");
2121    }
2122    s
2123}
2124
2125/// Render a `ConsultReport` (Task 11 / §C.3 Mode-2 read-only pre-trade what-if) for the
2126/// `optimize consult` command. Returns a String with:
2127///   - The hypothetical sale header (sat amount, wallet, date).
2128///   - The proposed lot selection (the tax-minimizing picks).
2129///   - The ST/LT gain split and the federal tax attributable to this contemplated sale.
2130///   - When `timing.is_some()`: the ST→LT crossover line (crossover date + saving), OMITTED when None.
2131///   - A footer: tax decision-support only, not investment advice.
2132///
2133/// **READ-ONLY:** this function only renders; it never writes any event or side-table row.
2134pub fn render_consult(r: &btctax_core::ConsultReport) -> String {
2135    let mut s = String::new();
2136    let _ = writeln!(
2137        s,
2138        "Consult (read-only what-if): sell {} sat from {} on {}",
2139        r.req.sell_sat,
2140        wallet_label(&r.req.wallet),
2141        r.req.at
2142    );
2143    // C-M2: for large pools (>12 lots) the candidate set is a heuristic subset — disclose it.
2144    if r.approximate {
2145        let _ = writeln!(
2146            s,
2147            "  \u{26a0} heuristic \u{2014} searched a subset of a large (>12-lot) pool; \
2148             the proposed selection may not be the exact minimum."
2149        );
2150    }
2151    let _ = writeln!(
2152        s,
2153        "  proposed selection: {}",
2154        picks_str(&r.proposed_selection)
2155    );
2156    let _ = writeln!(
2157        s,
2158        "  short-term gain: {}   long-term gain: {}",
2159        r.st_gain, r.lt_gain
2160    );
2161    // [consult fix] Headline the sale's OWN marginal effect (withhyp − baseline); keep the whole-year
2162    // figure clearly relabeled below it (on a year with real disposals the two DIFFER).
2163    let _ = writeln!(s, "  marginal federal tax (this sale): {}", r.marginal_tax);
2164    let _ = writeln!(
2165        s,
2166        "  whole-year federal tax attributable (with this sale): {}",
2167        r.total_federal_tax_attributable
2168    );
2169    if let Some(t) = &r.timing {
2170        let _ = writeln!(
2171            s,
2172            "  timing: {} sat of the best selection is short-term until {}; \
2173             selling on/after then would be taxed long-term, a \u{2248} {} difference.",
2174            t.st_sat_in_selection, t.latest_crossover, t.saving_if_waited
2175        );
2176    }
2177    let _ = writeln!(
2178        s,
2179        "Tax decision-support only \u{2014} consequences of a contemplated sale; \
2180         not investment advice (no buy/sell/hold recommendation)."
2181    );
2182    s
2183}
2184
2185/// The §1(h) 0/15/20 rate zone label for the sale's preferential dollars.
2186fn ltcg_bracket_label(b: LtcgBracket) -> &'static str {
2187    match b {
2188        LtcgBracket::Zero => "0%",
2189        LtcgBracket::Fifteen => "15%",
2190        LtcgBracket::Twenty => "20%",
2191    }
2192}
2193
2194/// Render a `what-if sell` `SellReport` (task #43). Headlines the MARGINAL federal tax (the sale's OWN
2195/// effect — `withhyp − baseline`), then the §1(h) bracket + room, the effective rate (or n/a for a loss),
2196/// the §1212 carryforward disclosure (delta-based — the this-year ordinary offset AND the amount carried,
2197/// NEVER a hard-coded $3,000), and the §1411 NIIT delta with its sign. `magi_caveat` prints the
2198/// ad-hoc-profile "MAGI assumed = ordinary income" note. Read-only; the vault is never touched.
2199pub fn render_whatif_sell(r: &SellReport, magi_caveat: bool) -> String {
2200    let mut s = String::new();
2201    let _ = writeln!(
2202        s,
2203        "What-if (read-only): sell {} sat from {} on {}",
2204        r.req.sell_sat,
2205        wallet_label(&r.req.wallet),
2206        r.req.at
2207    );
2208    if magi_caveat {
2209        let _ = writeln!(
2210            s,
2211            "  \u{26a0} MAGI assumed = ordinary income; NIIT may be understated if you have other MAGI."
2212        );
2213    }
2214    let _ = writeln!(s, "  proceeds: {}", r.proceeds);
2215    let _ = writeln!(s, "  lots consumed:");
2216    for leg in &r.lots {
2217        let term = match leg.term {
2218            Term::ShortTerm => "ST",
2219            Term::LongTerm => "LT",
2220        };
2221        let _ = writeln!(
2222            s,
2223            "    {}#{}  {} sat  basis {}  {} \u{2192} {}  {}  gain {}",
2224            leg.lot_id.origin_event_id.canonical(),
2225            leg.lot_id.split_sequence,
2226            leg.sat,
2227            leg.basis,
2228            leg.acquired_at,
2229            leg.sold_at,
2230            term,
2231            leg.gain
2232        );
2233    }
2234    let _ = writeln!(
2235        s,
2236        "  short-term gain: {}   long-term gain: {}",
2237        r.st_gain, r.lt_gain
2238    );
2239    // §1(h) bracket + headroom to the next breakpoint.
2240    match r.bracket_room {
2241        Some(room) => {
2242            let _ = writeln!(
2243                s,
2244                "  \u{00a7}1(h) LTCG bracket: {} (room {} before the next breakpoint)",
2245                ltcg_bracket_label(r.bracket),
2246                room
2247            );
2248        }
2249        None => {
2250            let _ = writeln!(
2251                s,
2252                "  \u{00a7}1(h) LTCG bracket: {} (top bracket \u{2014} no headroom)",
2253                ltcg_bracket_label(r.bracket)
2254            );
2255        }
2256    }
2257    // The headline: the sale's OWN marginal federal tax.
2258    let _ = writeln!(s, "  marginal federal tax (this sale): {}", r.marginal_tax);
2259    match r.effective_rate {
2260        Some(rate) => {
2261            let _ = writeln!(s, "  effective rate: {rate}");
2262        }
2263        None => {
2264            let _ = writeln!(
2265                s,
2266                "  effective rate: n/a (a loss/zero-gain sale \u{2014} its value is the carryforward, \
2267                 not this-year tax)"
2268            );
2269        }
2270    }
2271    // §1212 disclosure — delta-based, NEVER a hard-coded $3,000. Shown whenever a loss is carried OR the
2272    // sale unlocks a this-year ordinary offset.
2273    let carried = r.carryforward_delta.short + r.carryforward_delta.long;
2274    if carried != Usd::ZERO || r.ordinary_offset_delta != Usd::ZERO {
2275        let _ = writeln!(
2276            s,
2277            "  \u{00a7}1212: {} offsets ordinary income this year, {} carried to next year \
2278             (short {} / long {})",
2279            r.ordinary_offset_delta, carried, r.carryforward_delta.short, r.carryforward_delta.long
2280        );
2281    }
2282    // §1411 NIIT delta (with its sign) — only when the sale actually moved NIIT.
2283    if r.niit_applies {
2284        let dir = if r.niit_incremental < Usd::ZERO {
2285            "decrease"
2286        } else {
2287            "increase"
2288        };
2289        let _ = writeln!(
2290            s,
2291            "  \u{00a7}1411 NIIT: {} ({dir}) attributable to this sale",
2292            r.niit_incremental
2293        );
2294    }
2295    let status = match r.status {
2296        SellStatus::Gain => "net gain",
2297        SellStatus::Loss => "net loss (the carryforward is the value \u{2014} not this-year tax)",
2298    };
2299    let _ = writeln!(s, "  status: {status}");
2300    let _ = writeln!(
2301        s,
2302        "Tax decision-support only \u{2014} consequences of a contemplated sale; \
2303         not investment advice (no buy/sell/hold recommendation)."
2304    );
2305    s
2306}
2307
2308/// A human label for a harvest target.
2309fn harvest_target_label(t: &HarvestTarget) -> String {
2310    match t {
2311        HarvestTarget::ZeroLtcg => {
2312            "zero-ltcg (all gain in the \u{00a7}1(h) 0% bracket)".to_string()
2313        }
2314        HarvestTarget::FifteenLtcg => "fifteen-ltcg (stay at/under 15%)".to_string(),
2315        HarvestTarget::Gain(x) => format!("gain \u{2264} {x}"),
2316        HarvestTarget::Tax(x) => format!("marginal tax \u{2264} {x}"),
2317    }
2318}
2319
2320/// Render a `what-if harvest` `HarvestReport` (task #43). Headlines the MAX BTC to sell (N*), the binding
2321/// constraint, the realized ST/LT split at N*, which §1(h) bracket the surviving preferential dollars
2322/// land in, the exact marginal federal tax, and the MANDATORY disclosures — the §1212(b) carryforward
2323/// delta/burn, the §1411 NIIT kink (a 0%/15% answer can still cost +3.8%), and the plateau note. The
2324/// answer is engine-verified. `magi_caveat` prints the ad-hoc "MAGI assumed = ordinary income" note.
2325pub fn render_whatif_harvest(r: &HarvestReport, magi_caveat: bool) -> String {
2326    let mut s = String::new();
2327    let _ = writeln!(
2328        s,
2329        "What-if HARVEST (read-only): {} from {} on {}",
2330        harvest_target_label(&r.req.target),
2331        wallet_label(&r.req.wallet),
2332        r.req.at
2333    );
2334    if magi_caveat {
2335        let _ = writeln!(
2336            s,
2337            "  \u{26a0} MAGI assumed = ordinary income; NIIT may be understated if you have other MAGI."
2338        );
2339    }
2340    let status = match &r.status {
2341        HarvestStatus::Found => "FOUND (the target binds)",
2342        HarvestStatus::NotBinding => "NOT BINDING (the whole position fits)",
2343        HarvestStatus::AlreadyBreached => "ALREADY BREACHED at N=0 (nothing can be harvested)",
2344        HarvestStatus::NoLots => "NO LOTS (nothing to harvest from that wallet)",
2345        HarvestStatus::ProceedsRequired => "PROCEEDS REQUIRED",
2346        HarvestStatus::PreTransitionYear => "PRE-2025 (a closed year, not a plan)",
2347        HarvestStatus::YearNotComputable(_) => "YEAR NOT COMPUTABLE",
2348    };
2349    let _ = writeln!(s, "  status: {status}");
2350    let _ = writeln!(s, "  \u{2192} sell up to {} BTC ({} sat)", r.n_btc, r.n_sat);
2351    let _ = writeln!(s, "  bound by: {}", r.binding_constraint);
2352    let _ = writeln!(
2353        s,
2354        "  realized gain at N*: short-term {}   long-term {}",
2355        r.st_gain, r.lt_gain
2356    );
2357    // §1(h) bracket of the surviving preferential dollars at N*.
2358    let ps = &r.with_result.pref_split;
2359    let bracket = if ps.at_20 > Usd::ZERO {
2360        "20%"
2361    } else if ps.at_15 > Usd::ZERO {
2362        "15%"
2363    } else {
2364        "0%"
2365    };
2366    let _ = writeln!(
2367        s,
2368        "  \u{00a7}1(h) preferential dollars at N*: {} in 0% / {} in 15% / {} in 20% (top bracket: {})",
2369        ps.at_0, ps.at_15, ps.at_20, bracket
2370    );
2371    let _ = writeln!(s, "  marginal federal tax at N*: {}", r.marginal_tax);
2372    // §1212 carryforward delta (burn = a gain absorbing a carried loss).
2373    let carried = r.carryforward_delta.short + r.carryforward_delta.long;
2374    if carried != Usd::ZERO {
2375        let dir = if carried < Usd::ZERO {
2376            "burned (spent)"
2377        } else {
2378            "carried to next year"
2379        };
2380        let _ = writeln!(
2381            s,
2382            "  \u{00a7}1212 carryforward {}: {} (short {} / long {})",
2383            dir, carried, r.carryforward_delta.short, r.carryforward_delta.long
2384        );
2385    }
2386    // §1411 NIIT kink — surfaced on bracket targets too (a 0%/15% answer can still cost +3.8%).
2387    if r.niit_applies {
2388        let dir = if r.niit_incremental < Usd::ZERO {
2389            "decrease"
2390        } else {
2391            "increase"
2392        };
2393        let _ = writeln!(
2394            s,
2395            "  \u{00a7}1411 NIIT: {} ({dir}) at N* \u{2014} the +3.8% kink applies even inside a 0%/15% bracket answer",
2396            r.niit_incremental
2397        );
2398    }
2399    if let Some(note) = &r.plateau_note {
2400        let _ = writeln!(s, "  \u{2139} {note}");
2401    }
2402    let _ = writeln!(
2403        s,
2404        "Tax decision-support only \u{2014} the engine-verified consequences of a contemplated harvest; \
2405         not investment advice (no buy/sell/hold recommendation)."
2406    );
2407    s
2408}
2409
2410pub fn render_verify(r: &VerifyReport) -> String {
2411    let mut out = String::new();
2412    let c = &r.conservation;
2413    let _ = writeln!(
2414        out,
2415        "Conservation (FR9): {}",
2416        if c.balanced { "BALANCED" } else { "DRIFT" }
2417    );
2418    let _ = writeln!(
2419        out,
2420        "  in {} = disposed {} + removed {} + held {} + fee-sats {} + pending {}{}",
2421        c.sigma_in,
2422        c.sigma_disposed,
2423        c.sigma_removed,
2424        c.sigma_held,
2425        c.sigma_fee_sats,
2426        c.sigma_pending,
2427        if c.has_uncovered {
2428            "  [identity undefined: uncovered disposal open]"
2429        } else {
2430            ""
2431        }
2432    );
2433    let _ = writeln!(out, "2025 transition: {}", r.safe_harbor);
2434    let _ = writeln!(
2435        out,
2436        "Pending reconciliation: {} transfer(s); unknown-basis inbounds: {}",
2437        r.pending, r.unknown_basis_inbounds
2438    );
2439
2440    let _ = writeln!(
2441        out,
2442        "Hard blockers (gate tax computation): {}",
2443        r.hard.len()
2444    );
2445    for b in &r.hard {
2446        let evt = b
2447            .event
2448            .as_ref()
2449            .map(|e| e.canonical())
2450            .unwrap_or_else(|| "-".to_string());
2451        let _ = writeln!(out, "  [{:?}] {} :: {}", b.kind, evt, b.detail);
2452        // #41 Part C: an FMV gap can be a missing daily close — point at the separate updater (a STRING
2453        // only; the tax binaries never fetch). Pseudo mode can also fill it from the cache (Part B).
2454        if b.kind == BlockerKind::FmvMissing {
2455            let _ = writeln!(out, "         ↳ {}", crate::price_cache::UPDATE_PRICES_HINT);
2456        }
2457    }
2458    let _ = writeln!(out, "Advisory blockers: {}", r.advisory.len());
2459    for b in &r.advisory {
2460        let evt = b
2461            .event
2462            .as_ref()
2463            .map(|e| e.canonical())
2464            .unwrap_or_else(|| "-".to_string());
2465        let _ = writeln!(out, "  [{:?}] {} :: {}", b.kind, evt, b.detail);
2466    }
2467    let _ = writeln!(
2468        out,
2469        "Pre-2025 method (attested historical fact): {} (attested: {})",
2470        lot_method_display(r.declared_pre2025_method),
2471        r.pre2025_method_attested
2472    );
2473    let _ = writeln!(
2474        out,
2475        "Standing orders (MethodElection): {}",
2476        r.elections.len()
2477    );
2478    for e in &r.elections {
2479        let _ = writeln!(
2480            out,
2481            "  recorded {} effective {} -> {} [{}]",
2482            e.recorded,
2483            e.effective_from,
2484            lot_method_display(e.method),
2485            e.note
2486        );
2487    }
2488    let _ = writeln!(out, "Lot selections recorded: {}", r.selection_count);
2489    let _ = writeln!(
2490        out,
2491        "Per-disposal compliance (post-2025): {}",
2492        r.compliance.len()
2493    );
2494    for c in &r.compliance {
2495        let _ = writeln!(
2496            out,
2497            "  {} @ {} :: {}",
2498            c.disposal.canonical(),
2499            c.date,
2500            compliance_status_tag(&c.status)
2501        );
2502    }
2503    out
2504}
2505
2506#[cfg(test)]
2507mod gift_advisory_tests {
2508    //! P2-C Task 3 KATs — `render_gift_advisory` (per-donee §2503(b) refactor, Chunk 2).
2509    //!
2510    //! Direct-state `Removal{Gift}` fixtures + a `BTreeMap<i32, TaxTable>` table double so the
2511    //! exclusion + no-table cases are under exact control. Exclusion = $19,000 (TY2025) throughout.
2512    //! PRIVACY: synthetic values only.
2513    use super::*;
2514    use btctax_core::conventions::Usd;
2515    use btctax_core::{EventId, LotId, Removal, RemovalLeg, TaxTable};
2516    use rust_decimal_macros::dec;
2517    use std::collections::BTreeMap;
2518    use time::macros::date;
2519
2520    /// Build an unlabeled (`donee: None`) Gift removal with a single leg of the given FMV.
2521    fn gift_removal(seq: u64, removed_at: TaxDate, fmv: Usd) -> Removal {
2522        Removal {
2523            event: EventId::decision(seq),
2524            kind: RemovalKind::Gift,
2525            removed_at,
2526            legs: vec![RemovalLeg {
2527                lot_id: LotId {
2528                    origin_event_id: EventId::decision(seq),
2529                    split_sequence: 0,
2530                },
2531                sat: 100,
2532                basis: dec!(0),
2533                fmv_at_transfer: fmv,
2534                term: Term::LongTerm,
2535                basis_source: BasisSource::ComputedFromCost,
2536                acquired_at: date!(2024 - 01 - 01),
2537                pseudo: false,
2538            }],
2539            appraisal_required: false,
2540            donor_acquired_at: None,
2541            claimed_deduction: None,
2542            donee: None,
2543        }
2544    }
2545    /// Build a labeled Gift removal (donee = `Some(label)`) using the same single-leg structure.
2546    fn gift_removal_labeled(seq: u64, removed_at: TaxDate, fmv: Usd, label: &str) -> Removal {
2547        Removal {
2548            donee: Some(label.to_string()),
2549            ..gift_removal(seq, removed_at, fmv)
2550        }
2551    }
2552    fn state_with(removals: Vec<Removal>) -> LedgerState {
2553        LedgerState {
2554            removals,
2555            ..Default::default()
2556        }
2557    }
2558    /// A table double carrying only the gift_annual_exclusion (ordinary/ltcg empty — unread here).
2559    /// Uses TY2025 lifetime exclusion ($13,990,000) as default; tests that need a different
2560    /// lifetime exclusion can use `tables_with_lifetime`.
2561    fn tables_with(year: i32, excl: Usd) -> BTreeMap<i32, TaxTable> {
2562        tables_with_lifetime(year, excl, dec!(13_990_000))
2563    }
2564
2565    /// Like `tables_with` but with an explicit `lifetime_excl` for §2505 boundary tests.
2566    fn tables_with_lifetime(year: i32, excl: Usd, lifetime_excl: Usd) -> BTreeMap<i32, TaxTable> {
2567        let mut m = BTreeMap::new();
2568        m.insert(
2569            year,
2570            TaxTable {
2571                year,
2572                source: "TEST",
2573                ordinary: BTreeMap::new(),
2574                ltcg: BTreeMap::new(),
2575                gift_annual_exclusion: excl,
2576                ss_wage_base: dec!(176100),
2577                gift_lifetime_exclusion: lifetime_excl,
2578            },
2579        );
2580        m
2581    }
2582
2583    // ── Preserved safety branches ────────────────────────────────────────────────────────────────
2584
2585    /// No gifts in the year → None (even with a table present). [R0-I2] safety preserved.
2586    #[test]
2587    fn no_gifts_is_none() {
2588        let st = state_with(vec![]);
2589        let tables = tables_with(2025, dec!(19000));
2590        assert!(render_gift_advisory(&st, 2025, dec!(0), &tables).is_none());
2591    }
2592
2593    /// [R0-m6] gifts present but NO bundled table → Some(note), NOT None (no silent skip).
2594    /// The no-table note records the total gifts so nothing is silently dropped.
2595    #[test]
2596    fn gifts_present_but_no_table_emits_note_not_none() {
2597        // Unlabeled gift — the no-table branch fires before per-donee grouping.
2598        let st = state_with(vec![gift_removal(1, date!(2026 - 06 - 01), dec!(50000))]);
2599        // Table double has 2025 only → table_for(2026) == None.
2600        let tables = tables_with(2025, dec!(19000));
2601        let msg =
2602            render_gift_advisory(&st, 2026, dec!(0), &tables).expect("note expected, not None");
2603        assert!(msg.contains("unavailable"), "{msg}");
2604        assert!(msg.contains("Form 709 exposure not evaluated"), "{msg}");
2605        assert!(
2606            msg.contains("50000.00"),
2607            "must record the gift total: {msg}"
2608        );
2609    }
2610
2611    // ── Labeled-donee over-exclusion ─────────────────────────────────────────────────────────────
2612
2613    /// A labeled donee over the exclusion → filing required advisory with the per-donee breakdown.
2614    /// (Replaces the stale `over_exclusion_emits_advisory_with_total_and_caveat` which asserted the
2615    /// now-removed "donee identity is not modeled" / "total-exposure signal" phrases.)
2616    #[test]
2617    fn labeled_donee_over_exclusion_emits_advisory() {
2618        let st = state_with(vec![gift_removal_labeled(
2619            1,
2620            date!(2025 - 06 - 01),
2621            dec!(20000),
2622            "Alice",
2623        )]);
2624        let tables = tables_with(2025, dec!(19000));
2625        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2626        assert!(msg.contains("20000.00"), "must show Alice's total: {msg}");
2627        assert!(msg.contains("19000.00"), "must show the exclusion: {msg}");
2628        assert!(
2629            msg.contains("Form 709 filing required"),
2630            "must flag filing required: {msg}"
2631        );
2632        assert!(msg.contains("Alice"), "must name Alice: {msg}");
2633        // taxable = 20000 − 19000 = 1000.
2634        assert!(msg.contains("1000.00"), "taxable must be $1000.00: {msg}");
2635        // The stale "donee identity is not modeled" caveat must be gone.
2636        assert!(
2637            !msg.contains("donee identity is not modeled"),
2638            "stale aggregate caveat must not appear: {msg}"
2639        );
2640    }
2641
2642    /// A labeled donee under the exclusion → advisory with "no filing required" (not None).
2643    /// (Replaces the stale `under_exclusion_is_none` which tested None for an unlabeled gift.)
2644    #[test]
2645    fn labeled_donee_under_exclusion_no_filing_required() {
2646        let st = state_with(vec![gift_removal_labeled(
2647            1,
2648            date!(2025 - 06 - 01),
2649            dec!(10000),
2650            "Alice",
2651        )]);
2652        let tables = tables_with(2025, dec!(19000));
2653        // Gifts present + labeled donee → always Some (per-donee breakdown shown).
2654        let msg =
2655            render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected, not None");
2656        assert!(
2657            msg.contains("No Form 709 filing required"),
2658            "must say no filing required: {msg}"
2659        );
2660        assert!(msg.contains("Alice"), "must mention Alice: {msg}");
2661        assert!(msg.contains("10000.00"), "must show Alice's total: {msg}");
2662    }
2663
2664    // ── KATs (hand-verified; TY2025 gift_annual_exclusion $19,000) ──────────────────────────────
2665
2666    /// KEY LOCK — per-donee under exclusion: Alice $15,000 + Bob $15,000 (aggregate $30,000 > $19k,
2667    /// but each < $19k) → NO filing required, $0 taxable. The OLD aggregate rule wrongly flagged
2668    /// this — this test proves per-donee §2503(b) is correctly applied.
2669    #[test]
2670    fn per_donee_under_exclusion_two_donees_no_filing_required() {
2671        let st = state_with(vec![
2672            gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(15000), "Alice"),
2673            gift_removal_labeled(2, date!(2025 - 06 - 01), dec!(15000), "Bob"),
2674        ]);
2675        let tables = tables_with(2025, dec!(19000));
2676        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2677        // No filing required — neither Alice nor Bob exceeds $19,000.
2678        assert!(
2679            msg.contains("No Form 709 filing required"),
2680            "neither donee exceeds exclusion → no filing required: {msg}"
2681        );
2682        // Both donees appear in the per-donee breakdown.
2683        assert!(msg.contains("Alice"), "Alice must appear: {msg}");
2684        assert!(msg.contains("Bob"), "Bob must appear: {msg}");
2685        // Both totals shown ($15,000 each).
2686        assert!(msg.contains("15000.00"), "donee total must appear: {msg}");
2687        // No labeled donee triggered the filing trigger.
2688        assert!(
2689            !msg.contains("Form 709 filing required (donee(s):"),
2690            "filing trigger must NOT fire: {msg}"
2691        );
2692        // Total taxable = $0 for both donees.
2693        assert!(
2694            msg.contains("Total taxable gifts: $0.00"),
2695            "total taxable must be $0.00: {msg}"
2696        );
2697    }
2698
2699    /// One labeled donee over exclusion: Alice $25,000 → filing required, taxable $6,000
2700    /// (= $25,000 − $19,000). Exact figures are hand-verified KAT values.
2701    #[test]
2702    fn one_donee_over_exclusion_filing_required() {
2703        let st = state_with(vec![gift_removal_labeled(
2704            1,
2705            date!(2025 - 06 - 01),
2706            dec!(25000),
2707            "Alice",
2708        )]);
2709        let tables = tables_with(2025, dec!(19000));
2710        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2711        assert!(
2712            msg.contains("Form 709 filing required (donee(s): Alice)"),
2713            "must trigger filing required for Alice: {msg}"
2714        );
2715        assert!(msg.contains("25000.00"), "Alice total must appear: {msg}");
2716        assert!(
2717            msg.contains("19000.00"),
2718            "exclusion applied must appear: {msg}"
2719        );
2720        // taxable = 25000 − 19000 = 6000.
2721        assert!(
2722            msg.contains("6000.00"),
2723            "taxable $6,000.00 must appear: {msg}"
2724        );
2725    }
2726
2727    /// Unlabeled bucket: a None-donee gift $30,000 → the unlabeled caveat + conservative aggregate
2728    /// signal (per-donee cannot be applied without a label). $30,000 > $19,000 → conservative signal.
2729    #[test]
2730    fn unlabeled_bucket_caveat_with_conservative_aggregate() {
2731        let st = state_with(vec![gift_removal(1, date!(2025 - 06 - 01), dec!(30000))]);
2732        let tables = tables_with(2025, dec!(19000));
2733        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2734        // Unlabeled caveat must appear.
2735        assert!(
2736            msg.contains("no donee label"),
2737            "unlabeled caveat must appear: {msg}"
2738        );
2739        assert!(
2740            msg.contains("30000.00"),
2741            "unlabeled total must appear: {msg}"
2742        );
2743        // Conservative aggregate signal: $30,000 > $19,000 (one exclusion).
2744        assert!(
2745            msg.contains("Conservative aggregate"),
2746            "conservative aggregate signal must appear: {msg}"
2747        );
2748        assert!(
2749            msg.contains("19000.00"),
2750            "one-exclusion comparison must appear: {msg}"
2751        );
2752        // No labeled-donee filing trigger must have fired.
2753        assert!(
2754            !msg.contains("Form 709 filing required (donee(s):"),
2755            "labeled filing trigger must NOT fire for unlabeled gifts: {msg}"
2756        );
2757    }
2758
2759    /// Mixed: Alice $25,000 (over exclusion) + unlabeled $5,000 → filing required for Alice +
2760    /// the unlabeled caveat for the $5,000 (which cannot have per-donee exclusion applied).
2761    #[test]
2762    fn mixed_labeled_over_and_unlabeled_shows_both() {
2763        let st = state_with(vec![
2764            gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(25000), "Alice"),
2765            gift_removal(2, date!(2025 - 06 - 01), dec!(5000)), // unlabeled
2766        ]);
2767        let tables = tables_with(2025, dec!(19000));
2768        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2769        // Alice triggers the filing required signal.
2770        assert!(
2771            msg.contains("Form 709 filing required"),
2772            "filing required for Alice: {msg}"
2773        );
2774        assert!(msg.contains("Alice"), "Alice must appear: {msg}");
2775        // Unlabeled caveat must also appear for the $5,000 gift.
2776        assert!(
2777            msg.contains("no donee label"),
2778            "unlabeled caveat must appear: {msg}"
2779        );
2780        assert!(
2781            msg.contains("5000.00"),
2782            "unlabeled total must appear: {msg}"
2783        );
2784    }
2785
2786    /// Donations excluded: a `Removal{Donation}` does NOT count as a Gift → advisory returns None
2787    /// (no Gift events in the year). Form 709 is §2503(b) — Gifts only; §170 Donations are separate.
2788    #[test]
2789    fn donations_excluded_from_form709_advisory() {
2790        let donation_removal = Removal {
2791            event: EventId::decision(1),
2792            kind: RemovalKind::Donation,
2793            removed_at: date!(2025 - 06 - 01),
2794            legs: vec![RemovalLeg {
2795                lot_id: LotId {
2796                    origin_event_id: EventId::decision(1),
2797                    split_sequence: 0,
2798                },
2799                sat: 100,
2800                basis: dec!(0),
2801                fmv_at_transfer: dec!(50000), // large FMV — must NOT trigger the advisory
2802                term: Term::LongTerm,
2803                basis_source: BasisSource::ComputedFromCost,
2804                acquired_at: date!(2024 - 01 - 01),
2805                pseudo: false,
2806            }],
2807            appraisal_required: false,
2808            donor_acquired_at: None,
2809            claimed_deduction: Some(dec!(50000)),
2810            donee: Some("Charity X".to_string()),
2811        };
2812        let st = state_with(vec![donation_removal]);
2813        let tables = tables_with(2025, dec!(19000));
2814        // A Donation is NOT a Gift → any_gift == false → advisory returns None.
2815        assert!(
2816            render_gift_advisory(&st, 2025, dec!(0), &tables).is_none(),
2817            "Donation must be excluded from the Form 709 advisory"
2818        );
2819    }
2820
2821    // ── Chunk-3a §2505 KATs (hand-verified; TY2025: annual $19,000, lifetime $13,990,000) ────────
2822
2823    /// [KAT-U] Under lifetime — Alice $100,000 gift, prior $0.
2824    /// current-year taxable = $81,000 (100k − 19k); used $81,000; remaining $13,909,000.
2825    /// No "EXCEEDED" line.
2826    #[test]
2827    fn section_2505_under_lifetime_shows_used_and_remaining() {
2828        let st = state_with(vec![gift_removal_labeled(
2829            1,
2830            date!(2025 - 06 - 01),
2831            dec!(100000),
2832            "Alice",
2833        )]);
2834        let tables = tables_with(2025, dec!(19000)); // lifetime = $13,990,000 via tables_with
2835        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2836        // current-year taxable = 100000 − 19000 = 81000
2837        assert!(
2838            msg.contains("81000.00"),
2839            "taxable $81,000 must appear: {msg}"
2840        );
2841        // §2505 block: used $81,000 of $13,990,000
2842        assert!(
2843            msg.contains("§2505 lifetime (basic) exclusion"),
2844            "§2505 block must appear: {msg}"
2845        );
2846        assert!(
2847            msg.contains("13990000.00"),
2848            "lifetime exclusion $13,990,000 must appear: {msg}"
2849        );
2850        // remaining = 13,990,000 − 81,000 = 13,909,000
2851        assert!(
2852            msg.contains("13909000.00"),
2853            "remaining $13,909,000 must appear: {msg}"
2854        );
2855        // No "EXCEEDED" — still under lifetime
2856        assert!(
2857            !msg.contains("EXCEEDED"),
2858            "must NOT say EXCEEDED when under limit: {msg}"
2859        );
2860        // [I1] stale Chunk-3 caveat is gone
2861        assert!(
2862            !msg.contains("later chunk (Chunk 3)"),
2863            "stale Chunk-3 caveat must be absent: {msg}"
2864        );
2865    }
2866
2867    /// [KAT-P] Prior gifts accumulate — Alice $100,000, prior $13,900,000.
2868    /// cumulative = 13,900,000 + 81,000 = 13,981,000; remaining = $9,000; no tax.
2869    #[test]
2870    fn section_2505_prior_gifts_accumulate() {
2871        let st = state_with(vec![gift_removal_labeled(
2872            1,
2873            date!(2025 - 06 - 01),
2874            dec!(100000),
2875            "Alice",
2876        )]);
2877        let tables = tables_with(2025, dec!(19000));
2878        let msg =
2879            render_gift_advisory(&st, 2025, dec!(13_900_000), &tables).expect("advisory expected");
2880        // cumulative = 13,900,000 + 81,000 = 13,981,000
2881        assert!(
2882            msg.contains("13981000.00"),
2883            "cumulative $13,981,000 must appear: {msg}"
2884        );
2885        // remaining = 13,990,000 − 13,981,000 = 9,000
2886        assert!(
2887            msg.contains("9000.00"),
2888            "remaining $9,000 must appear: {msg}"
2889        );
2890        assert!(
2891            !msg.contains("EXCEEDED"),
2892            "must NOT say EXCEEDED when under limit: {msg}"
2893        );
2894    }
2895
2896    /// [KAT-E] Exceeds lifetime — Alice $100,000, prior $13,950,000.
2897    /// cumulative = 13,950,000 + 81,000 = 14,031,000 > 13,990,000.
2898    /// excess = 14,031,000 − 13,990,000 = 41,000.
2899    #[test]
2900    fn section_2505_exceeds_lifetime_shows_exceeded_and_excess() {
2901        let st = state_with(vec![gift_removal_labeled(
2902            1,
2903            date!(2025 - 06 - 01),
2904            dec!(100000),
2905            "Alice",
2906        )]);
2907        let tables = tables_with(2025, dec!(19000));
2908        let msg =
2909            render_gift_advisory(&st, 2025, dec!(13_950_000), &tables).expect("advisory expected");
2910        assert!(
2911            msg.contains("14031000.00"),
2912            "cumulative $14,031,000 must appear: {msg}"
2913        );
2914        assert!(
2915            msg.contains("EXCEEDED"),
2916            "must say EXCEEDED when over lifetime limit: {msg}"
2917        );
2918        // excess = 41,000
2919        assert!(
2920            msg.contains("41000.00"),
2921            "excess $41,000 must appear: {msg}"
2922        );
2923    }
2924
2925    /// [KAT-B / R0-M2] Exact boundary — cumulative EXACTLY $13,990,000.
2926    /// Alice $100,000, prior = 13,990,000 − 81,000 = 13,909,000.
2927    /// remaining = $0; NOT "EXCEEDED" (strict `>`, not `>=`).
2928    #[test]
2929    fn section_2505_exact_boundary_remaining_zero_not_exceeded() {
2930        let st = state_with(vec![gift_removal_labeled(
2931            1,
2932            date!(2025 - 06 - 01),
2933            dec!(100000),
2934            "Alice",
2935        )]);
2936        let tables = tables_with(2025, dec!(19000));
2937        // prior = 13,990,000 − 81,000 = 13,909,000 → cumulative = 13,990,000 exactly
2938        let msg =
2939            render_gift_advisory(&st, 2025, dec!(13_909_000), &tables).expect("advisory expected");
2940        assert!(
2941            msg.contains("13990000.00"),
2942            "cumulative $13,990,000 must appear: {msg}"
2943        );
2944        // remaining = 0 — assert the exact phrasing so "13990000.00" cannot satisfy this
2945        assert!(
2946            msg.contains("($0.00 remaining)"),
2947            "remaining $0.00 in exact phrasing '($0.00 remaining)' must appear: {msg}"
2948        );
2949        // strict >: at exactly the limit, NOT exceeded
2950        assert!(
2951            !msg.contains("EXCEEDED"),
2952            "must NOT say EXCEEDED at exactly the limit: {msg}"
2953        );
2954    }
2955
2956    /// [KAT-P4 / R0-M4] Prior-only edge — prior $5,000,000, all current donees under annual.
2957    /// Alice $10,000 gift (under $19k annual) → current taxable $0.
2958    /// cumulative = 5,000,000 + 0 = 5,000,000 > 0 → §2505 block SHOWS.
2959    #[test]
2960    fn section_2505_prior_only_block_shows_even_when_current_taxable_zero() {
2961        let st = state_with(vec![gift_removal_labeled(
2962            1,
2963            date!(2025 - 06 - 01),
2964            dec!(10000), // under $19k annual exclusion → current taxable = 0
2965            "Alice",
2966        )]);
2967        let tables = tables_with(2025, dec!(19000));
2968        let msg =
2969            render_gift_advisory(&st, 2025, dec!(5_000_000), &tables).expect("advisory expected");
2970        // cumulative = 5,000,000 (from prior; current taxable = 0)
2971        assert!(
2972            msg.contains("5000000.00"),
2973            "cumulative $5,000,000 must appear: {msg}"
2974        );
2975        assert!(
2976            msg.contains("§2505 lifetime (basic) exclusion"),
2977            "§2505 block must appear for prior-only case: {msg}"
2978        );
2979        assert!(!msg.contains("EXCEEDED"), "must NOT say EXCEEDED: {msg}");
2980    }
2981
2982    /// [KAT-N] No taxable gifts → no §2505 block.
2983    /// Alice $10,000 (under annual), prior $0 → cumulative = $0 → no §2505 line.
2984    #[test]
2985    fn section_2505_no_block_when_cumulative_zero() {
2986        let st = state_with(vec![gift_removal_labeled(
2987            1,
2988            date!(2025 - 06 - 01),
2989            dec!(10000), // under $19k annual exclusion
2990            "Alice",
2991        )]);
2992        let tables = tables_with(2025, dec!(19000));
2993        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
2994        assert!(
2995            !msg.contains("§2505 lifetime"),
2996            "§2505 block must NOT appear when cumulative = 0: {msg}"
2997        );
2998    }
2999
3000    /// [KAT-D0] Default $0 prior — no flag → prior $0 + the new caveats present (no stale Chunk-3).
3001    #[test]
3002    fn section_2505_default_zero_prior_shows_caveats() {
3003        let st = state_with(vec![gift_removal_labeled(
3004            1,
3005            date!(2025 - 06 - 01),
3006            dec!(100000), // taxable $81k
3007            "Alice",
3008        )]);
3009        let tables = tables_with(2025, dec!(19000));
3010        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3011        // [I1] stale Chunk-3 caveat is ABSENT
3012        assert!(
3013            !msg.contains("later chunk (Chunk 3)"),
3014            "stale 'later chunk (Chunk 3)' must be absent: {msg}"
3015        );
3016        // New caveats present
3017        assert!(
3018            msg.contains("§2513 gift-splitting"),
3019            "§2513 caveat must be present: {msg}"
3020        );
3021        assert!(
3022            msg.contains("portability/DSUE"),
3023            "portability/DSUE caveat must be present: {msg}"
3024        );
3025        assert!(
3026            msg.contains("prior cumulative taxable gifts are user-supplied"),
3027            "prior-cumulative disclosure caveat must be present: {msg}"
3028        );
3029    }
3030
3031    /// [KAT-I2] Mixed/unlabeled — Alice $100,000 (taxable $81k) + unlabeled $50,000.
3032    /// §2505 block shows used $81k AND the unlabeled-omission disclosure line.
3033    #[test]
3034    fn section_2505_mixed_shows_omission_disclosure_for_unlabeled() {
3035        let st = state_with(vec![
3036            gift_removal_labeled(1, date!(2025 - 03 - 01), dec!(100000), "Alice"),
3037            gift_removal(2, date!(2025 - 06 - 01), dec!(50000)), // unlabeled
3038        ]);
3039        let tables = tables_with(2025, dec!(19000));
3040        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3041        // §2505 block shows used $81,000 (LABELED only)
3042        assert!(
3043            msg.contains("§2505 lifetime (basic) exclusion"),
3044            "§2505 block must appear: {msg}"
3045        );
3046        assert!(
3047            msg.contains("81000.00"),
3048            "used $81,000 (labeled only) must appear: {msg}"
3049        );
3050        // [I2] Unlabeled-omission disclosure in §2505 block
3051        assert!(
3052            msg.contains("§2505 consumption reflects LABELED-donee taxable gifts only"),
3053            "omission disclosure must appear: {msg}"
3054        );
3055        assert!(
3056            msg.contains("50000.00"),
3057            "unlabeled total $50,000 must appear in omission disclosure: {msg}"
3058        );
3059        assert!(
3060            msg.contains("consumption may be understated"),
3061            "under-stated warning must appear: {msg}"
3062        );
3063    }
3064
3065    /// [KAT-I1] Absence — the stale "§2505 … later chunk (Chunk 3)" string is GONE from output.
3066    #[test]
3067    fn section_2505_stale_chunk3_caveat_is_absent() {
3068        let st = state_with(vec![gift_removal_labeled(
3069            1,
3070            date!(2025 - 06 - 01),
3071            dec!(20000),
3072            "Alice",
3073        )]);
3074        let tables = tables_with(2025, dec!(19000));
3075        let msg = render_gift_advisory(&st, 2025, dec!(0), &tables).expect("advisory expected");
3076        assert!(
3077            !msg.contains("later chunk (Chunk 3)"),
3078            "stale Chunk-3 caveat must be absent: {msg}"
3079        );
3080        assert!(
3081            !msg.contains("§2505 lifetime exemption is a later chunk"),
3082            "stale §2505 future-chunk phrase must be absent: {msg}"
3083        );
3084    }
3085}
3086
3087#[cfg(test)]
3088mod schedule_se_tests {
3089    //! P2-D Task 2 / Chunk A + Chunk B KATs — `render_schedule_se` + `schedule_se.csv`.
3090    //! The rendered figures reuse hand-verified SeTaxResult fixtures (see btctax-core se.rs KATs).
3091    //! PRIVACY: synthetic values only.
3092    use super::*;
3093    use rust_decimal_macros::dec;
3094
3095    /// Golden 1 SeTaxResult (Single, $100,000 business mining, no W-2, no expenses).
3096    fn golden1() -> SeTaxResult {
3097        SeTaxResult {
3098            net_se: dec!(100000),
3099            base: dec!(92350.00),
3100            ss: dec!(11451.40),
3101            medicare: dec!(2678.15),
3102            addl: dec!(0.00),
3103            total: dec!(14129.55),
3104            deductible_half: dec!(7064.78),
3105        }
3106    }
3107
3108    /// [Chunk A] W-2 SeTaxResult: Single, mining $100k, w2_ss $150k, w2_medicare $150k.
3109    fn w2_headline() -> SeTaxResult {
3110        SeTaxResult {
3111            net_se: dec!(100000),
3112            base: dec!(92350.00),
3113            ss: dec!(3236.40),
3114            medicare: dec!(2678.15),
3115            addl: dec!(381.15),
3116            total: dec!(6295.70),
3117            deductible_half: dec!(2957.28),
3118        }
3119    }
3120
3121    /// [Chunk A] Asymmetric SeTaxResult: w2_ss $150k, w2_medicare $0.
3122    fn w2_asymmetric() -> SeTaxResult {
3123        SeTaxResult {
3124            net_se: dec!(100000),
3125            base: dec!(92350.00),
3126            ss: dec!(3236.40),
3127            medicare: dec!(2678.15),
3128            addl: dec!(0.00),
3129            total: dec!(5914.55),
3130            deductible_half: dec!(2957.28),
3131        }
3132    }
3133
3134    /// [Chunk B] Headline expenses SeTaxResult: Single, mining $100k, expenses $20k, no W-2.
3135    /// net_se = 80,000; base = 80,000 × 0.9235 = 73,880.00; ss = 12.4% × 73,880 = 9,161.12;
3136    /// medicare = 2.9% × 73,880 = 2,142.52; addl = 0; total = 11,303.64;
3137    /// deductible_half = (9,161.12 + 2,142.52)/2 = 5,651.82.
3138    fn expenses_headline() -> SeTaxResult {
3139        SeTaxResult {
3140            net_se: dec!(80000),
3141            base: dec!(73880.00),
3142            ss: dec!(9161.12),
3143            medicare: dec!(2142.52),
3144            addl: dec!(0.00),
3145            total: dec!(11303.64),
3146            deductible_half: dec!(5651.82),
3147        }
3148    }
3149
3150    /// [Chunk B] W-2 + expenses SeTaxResult: Single, mining $100k, expenses $20k, w2_ss $150k,
3151    /// w2_medicare $150k.
3152    /// net_se = 80,000; base = 73,880.00; ss_cap = max(0, 176,100 − 150,000) = 26,100 →
3153    /// ss = 12.4% × min(73,880, 26,100) = 12.4% × 26,100 = 3,236.40;
3154    /// medicare = 2.9% × 73,880 = 2,142.52;
3155    /// addl_threshold = max(0, 200,000 − 150,000) = 50,000; over = 73,880 − 50,000 = 23,880 →
3156    /// addl = 0.9% × 23,880 = 214.92;
3157    /// total = 3,236.40 + 2,142.52 + 214.92 = 5,593.84;
3158    /// deductible_half = (3,236.40 + 2,142.52)/2 = 2,689.46.
3159    fn expenses_w2_combined() -> SeTaxResult {
3160        SeTaxResult {
3161            net_se: dec!(80000),
3162            base: dec!(73880.00),
3163            ss: dec!(3236.40),
3164            medicare: dec!(2142.52),
3165            addl: dec!(214.92),
3166            total: dec!(5593.84),
3167            deductible_half: dec!(2689.46),
3168        }
3169    }
3170
3171    /// Business-mining year → full Schedule SE section: components + total + deductible half +
3172    /// [Chunk A] the $0-W-2 short note + the §164(f) advisory + the [D5] standalone note.
3173    /// [Chunk B] expenses $0 → "no Schedule C expenses supplied" note (old "not modeled" GONE).
3174    #[test]
3175    fn business_mining_year_renders_full_section() {
3176        let r = golden1();
3177        let s = render_schedule_se(
3178            2025,
3179            Some(&r),
3180            dec!(100000),
3181            true,
3182            Usd::ZERO,
3183            Usd::ZERO,
3184            Usd::ZERO,
3185        )
3186        .expect("SE section expected");
3187        // Components + total + §164(f) half.
3188        assert!(s.contains("92350.00"), "net SE earnings base: {s}");
3189        assert!(s.contains("11451.40"), "SS component: {s}");
3190        assert!(s.contains("2678.15"), "Medicare component: {s}");
3191        assert!(s.contains("14129.55"), "total SE tax: {s}");
3192        assert!(s.contains("7064.78"), "§164(f) deductible half: {s}");
3193        assert!(
3194            s.contains("Additional Medicare"),
3195            "addl component labeled: {s}"
3196        );
3197        // [Chunk A / R0-I2] NEW $0-W-2 short note present; old OVERSTATED/UNDERSTATED GONE.
3198        assert!(
3199            s.contains("$0 W-2 wages"),
3200            "short $0-W-2 note must appear (both W-2 = 0): {s}"
3201        );
3202        assert!(
3203            s.contains("--w2-ss-wages"),
3204            "$0 note must mention --w2-ss-wages flag: {s}"
3205        );
3206        assert!(
3207            !s.contains("OVERSTATED"),
3208            "old OVERSTATED text must be absent (Chunk A regression): {s}"
3209        );
3210        assert!(
3211            !s.contains("UNDERSTATED"),
3212            "old UNDERSTATED text must be absent (Chunk A regression): {s}"
3213        );
3214        // [Chunk A / R0-I3] §164(f) advisory present.
3215        assert!(
3216            s.contains("NOT auto-coordinated"),
3217            "§164(f) advisory must appear: {s}"
3218        );
3219        assert!(
3220            s.contains("coordinate it on your actual return"),
3221            "§164(f) advisory must include coordination instruction: {s}"
3222        );
3223        // [D5] standalone note.
3224        assert!(
3225            s.contains("SEPARATE federal liability"),
3226            "standalone note: {s}"
3227        );
3228        assert!(
3229            s.contains("not") && s.contains("§164(f)"),
3230            "notes §164(f) not auto-coordinated: {s}"
3231        );
3232        // [Chunk B] $0-expenses note replaces the old "not modeled" caveat.
3233        assert!(
3234            s.contains("no Schedule C expenses supplied"),
3235            "Chunk B $0-expenses note must appear: {s}"
3236        );
3237        assert!(
3238            s.contains("--schedule-c-expenses"),
3239            "$0 note must mention --schedule-c-expenses flag: {s}"
3240        );
3241        assert!(
3242            !s.contains("not modeled"),
3243            "old 'not modeled' caveat must be absent (replaced by Chunk B): {s}"
3244        );
3245    }
3246
3247    /// [Chunk A / D3] When W-2 values are set, the coordinated disclosure appears with §1401(b)(2)(B).
3248    #[test]
3249    fn w2_set_renders_coordinated_disclosure() {
3250        let r = w2_headline();
3251        let s = render_schedule_se(
3252            2025,
3253            Some(&r),
3254            dec!(100000),
3255            true,
3256            Usd::ZERO,
3257            dec!(150000),
3258            dec!(150000),
3259        )
3260        .expect("SE section expected");
3261        // [D3] Coordinated text present.
3262        assert!(
3263            s.contains("W-2 coordination applied"),
3264            "coordinated disclosure must appear: {s}"
3265        );
3266        assert!(
3267            s.contains("§1401(b)(2)(B)"),
3268            "must cite §1401(b)(2)(B): {s}"
3269        );
3270        assert!(
3271            s.contains("Form 8959 Part II"),
3272            "must cite Form 8959 Part II: {s}"
3273        );
3274        // The W-2 amounts appear in the disclosure text.
3275        assert!(s.contains("150000"), "w2_ss_wages amount must appear: {s}");
3276        // Old OVERSTATED/UNDERSTATED text ABSENT even in W-2 mode (expenses = 0).
3277        assert!(!s.contains("OVERSTATED"), "OVERSTATED must be absent: {s}");
3278        assert!(
3279            !s.contains("UNDERSTATED"),
3280            "UNDERSTATED must be absent: {s}"
3281        );
3282        // Figures correct.
3283        assert!(s.contains("3236.40"), "reduced SS component: {s}");
3284        assert!(s.contains("381.15"), "non-zero addl: {s}");
3285        assert!(s.contains("6295.70"), "reduced total: {s}");
3286        assert!(s.contains("2957.28"), "deductible_half: {s}");
3287    }
3288
3289    /// [Chunk A / I4] Asymmetric-W-2 transposition guard (render level): w2_ss $150k, w2_medicare $0 →
3290    /// ss == $3,236.40 AND addl == $0.00 in the rendered text.
3291    /// A swapped (w2_medicare, w2_ss) argument order at the call site would flip both values.
3292    #[test]
3293    fn w2_asymmetric_render_transposition_guard() {
3294        let r = w2_asymmetric();
3295        let s = render_schedule_se(
3296            2025,
3297            Some(&r),
3298            dec!(100000),
3299            true,
3300            Usd::ZERO,
3301            dec!(150000),
3302            Usd::ZERO,
3303        )
3304        .expect("SE section expected");
3305        // W-2 coordination text must appear (w2_ss > 0).
3306        assert!(
3307            s.contains("W-2 coordination applied"),
3308            "coordinated disclosure must appear: {s}"
3309        );
3310        // ss is reduced, addl is 0 — not transposed values.
3311        assert!(s.contains("3236.40"), "ss must be 3236.40 (reduced): {s}");
3312        assert!(
3313            s.contains("0.00"),
3314            "addl must be 0.00 (threshold un-reduced): {s}"
3315        );
3316        // The old OVERSTATED/UNDERSTATED is absent.
3317        assert!(!s.contains("OVERSTATED"), "{s}");
3318        assert!(!s.contains("UNDERSTATED"), "{s}");
3319    }
3320
3321    /// No business SE income → no Schedule SE section (None). [gross_se == 0 path]
3322    #[test]
3323    fn no_business_income_no_section() {
3324        assert!(
3325            render_schedule_se(2025, None, Usd::ZERO, true, Usd::ZERO, Usd::ZERO, Usd::ZERO)
3326                .is_none()
3327        );
3328    }
3329
3330    /// Business SE income present but no bundled table → the "SS wage base unavailable" note (no
3331    /// silent drop). [gross_se > 0 && !table_present path]
3332    #[test]
3333    fn business_income_but_no_table_emits_note() {
3334        let s = render_schedule_se(
3335            2099,
3336            None,
3337            dec!(100000),
3338            false,
3339            Usd::ZERO,
3340            Usd::ZERO,
3341            Usd::ZERO,
3342        )
3343        .expect("wage-base-unavailable note expected");
3344        assert!(s.contains("SS wage base unavailable"), "{s}");
3345        assert!(s.contains("2099"), "names the year: {s}");
3346        assert!(s.contains("no silent drop"), "{s}");
3347    }
3348
3349    // ── Chunk B golden KATs ────────────────────────────────────────────────────────────────────
3350
3351    /// [Chunk B] Headline: expenses $20k, no W-2 → breakout line + Schedule C advisory.
3352    /// Verifies: gross = net_se + expenses shown, advisory text present, NO old "not modeled" caveat.
3353    #[test]
3354    fn expenses_20k_no_w2_renders_breakout_and_advisory() {
3355        let r = expenses_headline(); // net_se = 80,000; expenses = 20,000 → gross = 100,000
3356        let s = render_schedule_se(
3357            2025,
3358            Some(&r),
3359            dec!(100000), // gross_se
3360            true,
3361            dec!(20000), // schedule_c_expenses
3362            Usd::ZERO,
3363            Usd::ZERO,
3364        )
3365        .expect("SE section expected");
3366        // Breakout line: gross − expenses = net SE
3367        assert!(
3368            s.contains("gross business income"),
3369            "breakout line must appear: {s}"
3370        );
3371        assert!(
3372            s.contains("100000.00"),
3373            "gross ($100k) must appear in breakout: {s}"
3374        );
3375        assert!(
3376            s.contains("20000.00"),
3377            "expenses ($20k) must appear in breakout: {s}"
3378        );
3379        assert!(
3380            s.contains("80000.00"),
3381            "net_se ($80k) must appear in breakout: {s}"
3382        );
3383        // Schedule C advisory: OVERSTATES text present; NO OTI-edit prescription.
3384        assert!(
3385            s.contains("OVERSTATES"),
3386            "Schedule C advisory OVERSTATES text: {s}"
3387        );
3388        assert!(
3389            s.contains("ORDINARY taxable income"),
3390            "advisory must mention ORDINARY taxable income: {s}"
3391        );
3392        assert!(
3393            s.contains("engine-side coordination is deferred"),
3394            "advisory must mention deferred coordination: {s}"
3395        );
3396        // NO OTI-edit prescription: must NOT say "reduce your ordinary_taxable_income" (spec D3).
3397        assert!(
3398            !s.contains("reduce your ordinary_taxable_income"),
3399            "NO OTI-edit prescription allowed (spec D3): {s}"
3400        );
3401        assert!(
3402            !s.contains("set --ordinary-taxable-income"),
3403            "NO OTI-edit prescription allowed (spec D3): {s}"
3404        );
3405        // Golden figures: base, ss, medicare, total, deductible_half.
3406        assert!(s.contains("73880.00"), "base $73,880: {s}");
3407        assert!(s.contains("9161.12"), "ss $9,161.12: {s}");
3408        assert!(s.contains("2142.52"), "medicare $2,142.52: {s}");
3409        assert!(s.contains("11303.64"), "total $11,303.64: {s}");
3410        assert!(s.contains("5651.82"), "deductible_half $5,651.82: {s}");
3411        // Old "not modeled" caveat is ABSENT.
3412        assert!(
3413            !s.contains("not modeled"),
3414            "old 'not modeled' caveat must be absent: {s}"
3415        );
3416    }
3417
3418    /// [Chunk B / R0-I1] Fully expensed (gross > 0, table present, net_se == 0) → the NEW
3419    /// "fully expensed" line; the "SS wage base unavailable" note ABSENT.
3420    #[test]
3421    fn fully_expensed_shows_new_line_not_wage_base_note() {
3422        // mining $10,000, expenses $15,000 → net_se = 0 → compute_se_tax returns None.
3423        // Render with gross_se = 10,000 and table_present = true.
3424        let s = render_schedule_se(
3425            2025,
3426            None,
3427            dec!(10000), // gross_se
3428            true,        // table_present = true
3429            dec!(15000), // schedule_c_expenses
3430            Usd::ZERO,
3431            Usd::ZERO,
3432        )
3433        .expect("fully-expensed section expected (not None)");
3434        // The new "fully expensed" line is present.
3435        assert!(
3436            s.contains("fully expensed"),
3437            "fully-expensed line must appear: {s}"
3438        );
3439        assert!(
3440            s.contains("10000.00"),
3441            "gross $10k must appear in fully-expensed line: {s}"
3442        );
3443        assert!(
3444            s.contains("15000.00"),
3445            "expenses $15k must appear in fully-expensed line: {s}"
3446        );
3447        assert!(
3448            s.contains("no §1401 SE tax"),
3449            "must state no SE tax owed: {s}"
3450        );
3451        assert!(s.contains("2025"), "must name the year: {s}");
3452        // The "SS wage base unavailable" note is ABSENT (negative assertion per [R0-I1]).
3453        assert!(
3454            !s.contains("SS wage base unavailable"),
3455            "wage-base-unavailable note must be ABSENT for fully-expensed case: {s}"
3456        );
3457    }
3458
3459    /// [Chunk B] W-2 + expenses combined render: breakout and W-2 coordination both appear.
3460    #[test]
3461    fn expenses_w2_combined_renders_both() {
3462        let r = expenses_w2_combined(); // net_se = 80,000; gross = 100,000; expenses = 20,000
3463        let s = render_schedule_se(
3464            2025,
3465            Some(&r),
3466            dec!(100000),
3467            true,
3468            dec!(20000),  // schedule_c_expenses
3469            dec!(150000), // w2_ss_wages
3470            dec!(150000), // w2_medicare_wages
3471        )
3472        .expect("SE section expected");
3473        // Breakout line.
3474        assert!(s.contains("gross business income"), "breakout line: {s}");
3475        assert!(s.contains("80000.00"), "net_se in breakout: {s}");
3476        // Schedule C advisory.
3477        assert!(s.contains("OVERSTATES"), "Schedule C advisory: {s}");
3478        // W-2 coordination also present.
3479        assert!(
3480            s.contains("W-2 coordination applied"),
3481            "W-2 coordination: {s}"
3482        );
3483        // Figures correct.
3484        assert!(s.contains("73880.00"), "base: {s}");
3485        assert!(s.contains("3236.40"), "ss (reduced by W-2 cap): {s}");
3486        assert!(s.contains("2142.52"), "medicare: {s}");
3487        assert!(s.contains("214.92"), "addl: {s}");
3488        assert!(s.contains("5593.84"), "total: {s}");
3489        assert!(s.contains("2689.46"), "deductible_half: {s}");
3490    }
3491
3492    /// `schedule_se.csv` columns + values (year-scoped; written when a SeTaxResult exists).
3493    #[test]
3494    fn schedule_se_csv_columns_and_values() {
3495        let dir = tempfile::tempdir().unwrap();
3496        let out = dir.path().join("export");
3497        let st = LedgerState::default();
3498        let r = golden1();
3499        write_csv_exports(&out, &st, Some(2025), Some(&r), &BTreeMap::new()).unwrap();
3500
3501        let path = out.join("schedule_se.csv");
3502        assert!(path.exists(), "schedule_se.csv must be written");
3503        let mut rdr = csv::Reader::from_reader(std::fs::File::open(&path).unwrap());
3504        let headers: Vec<String> = rdr.headers().unwrap().iter().map(String::from).collect();
3505        assert_eq!(
3506            headers,
3507            vec![
3508                "net_se_earnings",
3509                "se_base_9235",
3510                "ss_component",
3511                "medicare_component",
3512                "additional_medicare_component",
3513                "total_se_tax",
3514                "deductible_half",
3515            ]
3516        );
3517        let rec = rdr
3518            .records()
3519            .next()
3520            .expect("one data row")
3521            .expect("readable");
3522        assert_eq!(&rec[0], "100000"); // net_se_earnings
3523        assert_eq!(&rec[1], "92350.00"); // se_base_9235
3524        assert_eq!(&rec[2], "11451.40"); // ss_component
3525        assert_eq!(&rec[3], "2678.15"); // medicare_component
3526        assert_eq!(&rec[4], "0.00"); // additional_medicare_component
3527        assert_eq!(&rec[5], "14129.55"); // total_se_tax
3528        assert_eq!(&rec[6], "7064.78"); // deductible_half
3529    }
3530
3531    /// No SeTaxResult → schedule_se.csv is NOT written (nothing to file; also covers fully-expensed).
3532    #[test]
3533    fn schedule_se_csv_omitted_when_no_se_tax() {
3534        let dir = tempfile::tempdir().unwrap();
3535        let out = dir.path().join("export");
3536        let st = LedgerState::default();
3537        write_csv_exports(&out, &st, Some(2025), None, &BTreeMap::new()).unwrap();
3538        assert!(!out.join("schedule_se.csv").exists());
3539    }
3540}
3541
3542#[cfg(test)]
3543mod form8283_csv_tests {
3544    //! P2-C / Chunk-3b Task 2 unit KATs — `write_form8283_csv` Part III/IV detail columns.
3545    //! Direct-state fixtures; pure unit (no vault). PRIVACY: synthetic values only.
3546    use super::*;
3547
3548    /// form8283.csv — new Part III/IV detail columns populated when details are present.
3549    #[test]
3550    fn form8283_csv_detail_columns_present_and_empty() {
3551        use btctax_core::{
3552            BasisSource, DonationDetails, EventId, LedgerState, Removal, RemovalKind, RemovalLeg,
3553            Term,
3554        };
3555        use time::macros::date;
3556
3557        let dir = tempfile::tempdir().unwrap();
3558        let out = dir.path().join("export");
3559
3560        // Build a minimal state with one Section-B donation.
3561        let event = EventId::decision(99);
3562        let leg = RemovalLeg {
3563            lot_id: btctax_core::LotId {
3564                origin_event_id: event.clone(),
3565                split_sequence: 0,
3566            },
3567            sat: 100_000_000,
3568            basis: rust_decimal::Decimal::ZERO,
3569            fmv_at_transfer: rust_decimal::Decimal::from(52000),
3570            term: Term::LongTerm,
3571            basis_source: BasisSource::ComputedFromCost,
3572            acquired_at: date!(2025 - 01 - 01),
3573            pseudo: false,
3574        };
3575        let removal = Removal {
3576            event: event.clone(),
3577            kind: RemovalKind::Donation,
3578            removed_at: date!(2025 - 03 - 01),
3579            legs: vec![leg],
3580            appraisal_required: false,
3581            donor_acquired_at: None,
3582            claimed_deduction: Some(rust_decimal::Decimal::from(52000)),
3583            donee: Some("Test Charity Two".into()),
3584        };
3585        // N1: second removal with NO details in dmap — locks the empty-half of the 6 new columns.
3586        let event2 = EventId::decision(100);
3587        let leg2 = RemovalLeg {
3588            lot_id: btctax_core::LotId {
3589                origin_event_id: event2.clone(),
3590                split_sequence: 0,
3591            },
3592            sat: 10_000_000,
3593            basis: rust_decimal::Decimal::ZERO,
3594            fmv_at_transfer: rust_decimal::Decimal::from(8000),
3595            term: Term::LongTerm,
3596            basis_source: BasisSource::ComputedFromCost,
3597            acquired_at: date!(2025 - 01 - 15),
3598            pseudo: false,
3599        };
3600        let removal2 = Removal {
3601            event: event2.clone(),
3602            kind: RemovalKind::Donation,
3603            removed_at: date!(2025 - 05 - 01),
3604            legs: vec![leg2],
3605            appraisal_required: false,
3606            donor_acquired_at: None,
3607            claimed_deduction: Some(rust_decimal::Decimal::from(8000)),
3608            donee: Some("No Details Org".into()),
3609        };
3610
3611        let st = LedgerState {
3612            removals: vec![removal, removal2],
3613            ..Default::default()
3614        };
3615
3616        let mut dmap: BTreeMap<EventId, DonationDetails> = BTreeMap::new();
3617        dmap.insert(
3618            event,
3619            DonationDetails {
3620                donee_name: "Test Charity".into(),
3621                donee_ein: Some("12-3456789".into()),
3622                donee_address: Some("123 Main".into()),
3623                appraiser_name: "Test Appraiser".into(),
3624                appraiser_tin: Some("987654321".into()),
3625                appraiser_ptin: Some("P01234567".into()),
3626                appraiser_qualifications: Some("Certified".into()),
3627                appraisal_date: Some(date!(2025 - 06 - 01)),
3628                appraiser_address: None,
3629                fmv_method_override: None,
3630            },
3631        );
3632        // event2 intentionally NOT inserted — exercises the empty-column path.
3633
3634        write_csv_exports(&out, &st, Some(2025), None, &dmap).unwrap();
3635
3636        let path = out.join("form8283.csv");
3637        assert!(path.exists(), "form8283.csv must exist");
3638
3639        let mut rdr = csv::ReaderBuilder::new()
3640            .comment(Some(b'#'))
3641            .from_path(&path)
3642            .unwrap();
3643        let headers: Vec<String> = rdr.headers().unwrap().iter().map(String::from).collect();
3644        let idx = |name: &str| {
3645            headers
3646                .iter()
3647                .position(|h| h == name)
3648                .unwrap_or_else(|| panic!("header {name} not found"))
3649        };
3650        // Collect both rows. form_8283 sorts by (removed_at, event, lot_id):
3651        //   records[0] = removal (removed_at 2025-03-01, event decision(99)) — WITH details.
3652        //   records[1] = removal2 (removed_at 2025-05-01, event decision(100)) — NO details.
3653        let all_recs: Vec<csv::StringRecord> = rdr.records().map(|r| r.unwrap()).collect();
3654        assert_eq!(
3655            all_recs.len(),
3656            2,
3657            "must have exactly two data rows (one per removal)"
3658        );
3659        let rec = &all_recs[0];
3660        let no_details_rec = &all_recs[1];
3661
3662        // WITH-details half: all 6 new columns populated.
3663        assert_eq!(&rec[idx("donee")], "Test Charity");
3664        assert_eq!(&rec[idx("appraiser")], "Test Appraiser");
3665        assert_eq!(&rec[idx("donee_ein")], "12-3456789");
3666        assert_eq!(&rec[idx("donee_address")], "123 Main");
3667        assert_eq!(&rec[idx("appraiser_tin")], "987654321");
3668        assert_eq!(&rec[idx("appraiser_ptin")], "P01234567");
3669        assert_eq!(&rec[idx("appraiser_qualifications")], "Certified");
3670        assert_eq!(&rec[idx("appraisal_date")], "2025-06-01");
3671        assert_eq!(&rec[idx("needs_review")], "false");
3672
3673        // N1: EMPTY half — no-details removal has all 6 new columns blank.
3674        assert_eq!(
3675            &no_details_rec[idx("donee_ein")],
3676            "",
3677            "no-details row: donee_ein must be empty"
3678        );
3679        assert_eq!(
3680            &no_details_rec[idx("donee_address")],
3681            "",
3682            "no-details row: donee_address must be empty"
3683        );
3684        assert_eq!(
3685            &no_details_rec[idx("appraiser_tin")],
3686            "",
3687            "no-details row: appraiser_tin must be empty"
3688        );
3689        assert_eq!(
3690            &no_details_rec[idx("appraiser_ptin")],
3691            "",
3692            "no-details row: appraiser_ptin must be empty"
3693        );
3694        assert_eq!(
3695            &no_details_rec[idx("appraiser_qualifications")],
3696            "",
3697            "no-details row: appraiser_qualifications must be empty"
3698        );
3699        assert_eq!(
3700            &no_details_rec[idx("appraisal_date")],
3701            "",
3702            "no-details row: appraisal_date must be empty"
3703        );
3704        assert_eq!(
3705            &no_details_rec[idx("needs_review")],
3706            "true",
3707            "no-details carrier row: needs_review must be true"
3708        );
3709    }
3710}
3711
3712/// UX-P4-11: one row of `events list` — a decidable event and its decision status. The `reff` is the
3713/// canonical event reference (`EventId::canonical()`) a `reconcile` verb accepts verbatim.
3714pub struct EventRow {
3715    /// The canonical event ref (pasteable into a reconcile verb). Named `reff` — `ref` is reserved.
3716    pub reff: String,
3717    /// A stable human kind tag: transfer-in | transfer-out | unclassified | import-conflict | income.
3718    pub kind: &'static str,
3719    /// The event's tax-timezone calendar date.
3720    pub date: TaxDate,
3721    /// Principal sats, when the payload carries a structured amount (None for unclassified/conflict).
3722    pub sat: Option<btctax_core::Sat>,
3723    /// USD value at the event-date close (stored FMV for income; else priced), when resolvable.
3724    pub usd: Option<Usd>,
3725    /// `Some("decision|N")` when a live (non-voided) decision targets this event; `None` = still
3726    /// decidable (a pseudo-defaulted event is decidable — its default is never persisted).
3727    pub decision_ref: Option<String>,
3728}
3729
3730/// Format sats as a BTC amount with 8 decimals (integer math — no float).
3731fn fmt_btc(sat: btctax_core::Sat) -> String {
3732    let whole = sat / 100_000_000;
3733    let frac = (sat % 100_000_000).unsigned_abs();
3734    format!("{whole}.{frac:08}")
3735}
3736
3737/// UX-P4-11: render the `events list` table. Ref-first per row (so it is trivially copyable), then
3738/// kind @ date, amount, and the bracketed decision status. Read-only display.
3739pub fn render_events_list(rows: &[EventRow]) -> String {
3740    let mut out = String::new();
3741    if rows.is_empty() {
3742        let _ = writeln!(out, "No decidable events.");
3743        return out;
3744    }
3745    let decided = rows.iter().filter(|r| r.decision_ref.is_some()).count();
3746    let _ = writeln!(
3747        out,
3748        "Decidable events — {} ({} decided, {} open):",
3749        rows.len(),
3750        decided,
3751        rows.len() - decided
3752    );
3753    for r in rows {
3754        let amount = match (r.sat, r.usd) {
3755            (Some(s), Some(u)) => format!("{} BTC (~${})", fmt_btc(s), fmt_money(u)),
3756            (Some(s), None) => format!("{} BTC", fmt_btc(s)),
3757            (None, _) => "—".to_string(),
3758        };
3759        let status = match &r.decision_ref {
3760            Some(d) => format!("[decided: {d}]"),
3761            None => "[decidable]".to_string(),
3762        };
3763        let _ = writeln!(
3764            out,
3765            "  {}  {} @ {}  {}  {}",
3766            r.reff, r.kind, r.date, amount, status
3767        );
3768    }
3769    out
3770}
3771
3772#[cfg(test)]
3773mod advisory_wrap_tests {
3774    use super::*;
3775
3776    /// `p5-n5-advisory-line-wrapping`: an advisory is a 300–400-character sentence, and the house style
3777    /// wraps everywhere else. An unwrapped one is unreadable in an 80-column terminal — and it is the ONE
3778    /// place the tool explains a conservative omission, so it is the text most worth reading.
3779    #[test]
3780    fn advisories_wrap_to_the_house_width_with_a_hanging_indent() {
3781        use btctax_core::tax::advisories::Advisory;
3782        let out = render_advisories(&[Advisory::CtcOdcOmitted { dependents: 2 }]);
3783
3784        for line in out.lines() {
3785            assert!(
3786                line.chars().count() <= ADVISORY_WRAP_COLS,
3787                "line is {} cols, over the {}-col house width: {line:?}",
3788                line.chars().count(),
3789                ADVISORY_WRAP_COLS
3790            );
3791        }
3792        // Continuation lines hang under the bullet's TEXT, not under the bullet.
3793        assert!(
3794            out.lines()
3795                .any(|l| l.starts_with("    ") && !l.trim().is_empty()),
3796            "a 300-char advisory must wrap onto continuation lines, got:\n{out}"
3797        );
3798    }
3799}
3800
3801#[cfg(test)]
3802mod events_list_render_tests {
3803    use super::*;
3804    use time::macros::date;
3805
3806    fn row(reff: &str, kind: &'static str, decision_ref: Option<&str>) -> EventRow {
3807        EventRow {
3808            reff: reff.to_owned(),
3809            kind,
3810            date: date!(2025 - 03 - 01),
3811            sat: Some(5_000_000),
3812            usd: Some(rust_decimal_macros::dec!(4271.78)),
3813            decision_ref: decision_ref.map(str::to_owned),
3814        }
3815    }
3816
3817    /// Empty → an explicit "none" line (never a blank rendering).
3818    #[test]
3819    fn empty_renders_a_none_line() {
3820        assert_eq!(render_events_list(&[]), "No decidable events.\n");
3821    }
3822
3823    /// Each row is ref-FIRST (trivially copyable), carries kind/date/BTC(+USD), and a bracketed status:
3824    /// `[decidable]` when open, `[decided: decision|N]` when a decision targets it.
3825    #[test]
3826    fn rows_are_ref_first_with_bracketed_status() {
3827        let out = render_events_list(&[
3828            row("import|coinbase|in|cb-recv", "transfer-in", None),
3829            row(
3830                "import|coinbase|out|cb-send",
3831                "transfer-out",
3832                Some("decision|1"),
3833            ),
3834        ]);
3835        let lines: Vec<&str> = out.lines().collect();
3836        assert!(
3837            lines[0].contains("2 (1 decided, 1 open)"),
3838            "header: {}",
3839            lines[0]
3840        );
3841        // ref is the first whitespace token on each row (the paste contract).
3842        assert_eq!(
3843            lines[1].split_whitespace().next(),
3844            Some("import|coinbase|in|cb-recv")
3845        );
3846        assert!(lines[1].contains("[decidable]"), "open row: {}", lines[1]);
3847        assert!(
3848            lines[1].contains("0.05000000 BTC") && lines[1].contains("4271.78"),
3849            "amount: {}",
3850            lines[1]
3851        );
3852        assert!(
3853            lines[2].contains("[decided: decision|1]"),
3854            "decided row: {}",
3855            lines[2]
3856        );
3857    }
3858}
3859
3860#[cfg(test)]
3861mod holdings_pending_tests {
3862    //! UX-P4-6 — the holdings view shows a BTC-unit pending line when sats sit unreconciled, and
3863    //! hides it on a reconciled ledger. `report` otherwise never mentioned pending (only `verify` did).
3864    use super::*;
3865    use btctax_core::state::PendingTransfer;
3866    use btctax_core::EventId;
3867
3868    #[test]
3869    fn holdings_pending_line_shows_in_btc_and_hides_when_reconciled() {
3870        let mut pending = LedgerState::default();
3871        pending.stats.sigma_pending = 3_000_000; // 0.03 BTC unreconciled
3872        pending.pending_reconciliation = vec![PendingTransfer {
3873            event: EventId::decision(1),
3874            principal_sat: 3_000_000,
3875            fee_sat: None,
3876            legs: vec![],
3877        }];
3878        let shown = render_report(&pending, None);
3879        assert!(shown.contains("Pending:"), "pending line present: {shown}");
3880        assert!(shown.contains("0.03000000 BTC"), "BTC unit: {shown}");
3881        assert!(
3882            shown.contains("1 unreconciled transfer"),
3883            "names the count (singular): {shown}"
3884        );
3885        assert!(shown.contains("verify"), "points at `verify`: {shown}");
3886
3887        // Reconciled ledger: no pending sats → no pending line at all.
3888        let reconciled = LedgerState::default();
3889        let hidden = render_report(&reconciled, None);
3890        assert!(
3891            !hidden.contains("Pending:"),
3892            "no pending line when reconciled: {hidden}"
3893        );
3894    }
3895
3896    #[test]
3897    fn holdings_pending_line_pluralizes_multiple_transfers() {
3898        let mut pending = LedgerState::default();
3899        pending.stats.sigma_pending = 150_000_000; // 1.5 BTC
3900        pending.pending_reconciliation = vec![
3901            PendingTransfer {
3902                event: EventId::decision(1),
3903                principal_sat: 100_000_000,
3904                fee_sat: None,
3905                legs: vec![],
3906            },
3907            PendingTransfer {
3908                event: EventId::decision(2),
3909                principal_sat: 50_000_000,
3910                fee_sat: None,
3911                legs: vec![],
3912            },
3913        ];
3914        let shown = render_report(&pending, None);
3915        assert!(
3916            shown.contains("2 unreconciled transfers"),
3917            "plural: {shown}"
3918        );
3919        assert!(shown.contains("1.50000000 BTC"), "{shown}");
3920    }
3921}
3922
3923#[cfg(test)]
3924mod decision_class_tests {
3925    //! UX-P4-7 — the shared SCREEN-ONLY human formatter for decision-payload class fields, replacing
3926    //! the raw `{:?}` Debug dumps (`SelfTransferMine { basis: Some(19000.00), acquired_at:
3927    //! Some(2026-01-01) }`) that the CLI bulk-void preview + TUI void list truncated mid-field.
3928    use super::*;
3929    use btctax_core::{DisposeKind, InboundClass, IncomeKind, OutflowClass};
3930    use rust_decimal_macros::dec;
3931    use time::macros::date;
3932
3933    #[test]
3934    fn inbound_self_transfer_mine_is_human_no_debug_struct() {
3935        let s = describe_inbound_class(&InboundClass::SelfTransferMine {
3936            basis: Some(dec!(19000)),
3937            acquired_at: Some(date!(2026 - 01 - 01)),
3938        });
3939        assert!(s.contains("self-transfer"), "{s}");
3940        assert!(s.contains("$19000.00"), "names the basis in $: {s}");
3941        assert!(s.contains("2026-01-01"), "names the acquired date: {s}");
3942        assert!(!s.contains('{'), "no Debug struct braces: {s}");
3943        assert!(!s.contains("Some("), "no Debug Option wrapper: {s}");
3944    }
3945
3946    #[test]
3947    fn inbound_self_transfer_mine_defaults_are_named_not_none() {
3948        let s = describe_inbound_class(&InboundClass::SelfTransferMine {
3949            basis: None,
3950            acquired_at: None,
3951        });
3952        assert!(s.contains("self-transfer"), "{s}");
3953        assert!(
3954            s.matches("default").count() >= 2,
3955            "None basis AND date read as 'default': {s}"
3956        );
3957        assert!(!s.contains("None"), "no Debug None: {s}");
3958    }
3959
3960    #[test]
3961    fn inbound_income_names_kind_fmv_business() {
3962        let s = describe_inbound_class(&InboundClass::Income {
3963            kind: IncomeKind::Mining,
3964            fmv: Some(dec!(500)),
3965            business: true,
3966        });
3967        assert!(s.contains("income"), "{s}");
3968        assert!(s.contains("mining"), "names the income kind: {s}");
3969        assert!(s.contains("$500.00"), "names the fmv: {s}");
3970        assert!(s.contains("business"), "flags business: {s}");
3971        assert!(!s.contains('{'), "{s}");
3972    }
3973
3974    #[test]
3975    fn inbound_gift_received_names_fmv() {
3976        let s = describe_inbound_class(&InboundClass::GiftReceived {
3977            donor_basis: Some(dec!(1000)),
3978            donor_acquired_at: Some(date!(2024 - 05 - 05)),
3979            fmv_at_gift: dec!(30000),
3980        });
3981        assert!(s.contains("gift"), "{s}");
3982        assert!(s.contains("$30000.00"), "names the FMV at gift: {s}");
3983        assert!(!s.contains('{'), "{s}");
3984    }
3985
3986    #[test]
3987    fn outflow_classes_are_human() {
3988        assert_eq!(
3989            describe_outflow_class(&OutflowClass::Dispose {
3990                kind: DisposeKind::Sell
3991            }),
3992            "sell"
3993        );
3994        assert_eq!(
3995            describe_outflow_class(&OutflowClass::Dispose {
3996                kind: DisposeKind::Spend
3997            }),
3998            "spend"
3999        );
4000        assert_eq!(describe_outflow_class(&OutflowClass::GiftOut), "gift");
4001        let donate = describe_outflow_class(&OutflowClass::Donate {
4002            appraisal_required: true,
4003        });
4004        assert!(
4005            donate.contains("donate") && donate.contains("appraisal"),
4006            "{donate}"
4007        );
4008        assert_eq!(
4009            describe_outflow_class(&OutflowClass::Donate {
4010                appraisal_required: false
4011            }),
4012            "donate"
4013        );
4014    }
4015}