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