rustledger-plugin-types 0.15.0

WASM plugin interface types for rustledger - use in your plugin crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! WASM Plugin Interface Types for rustledger
//!
//! This crate provides the type definitions for rustledger's WASM plugin interface.
//! Use it as a dependency in your plugin crate to ensure type compatibility with
//! the rustledger host.
//!
//! # Quick Start
//!
//! Add this to your plugin's `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! rustledger-plugin-types = "0.10"
//! rmp-serde = "1"
//! ```
//!
//! Then in your plugin:
//!
//! ```rust,ignore
//! use rustledger_plugin_types::*;
//!
//! #[no_mangle]
//! pub extern "C" fn process(input_ptr: u32, input_len: u32) -> u64 {
//!     let input_bytes = unsafe {
//!         std::slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
//!     };
//!
//!     let input: PluginInput = rmp_serde::from_slice(input_bytes).unwrap();
//!
//!     // Process directives — emit ops describing the output list.
//!     // Simplest case: keep every input unchanged.
//!     let output = PluginOutput::passthrough(input.directives.len());
//!
//!     let output_bytes = rmp_serde::to_vec(&output).unwrap();
//!     let output_ptr = alloc(output_bytes.len() as u32);
//!     unsafe {
//!         std::ptr::copy_nonoverlapping(
//!             output_bytes.as_ptr(),
//!             output_ptr,
//!             output_bytes.len(),
//!         );
//!     }
//!     ((output_ptr as u64) << 32) | (output_bytes.len() as u64)
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn alloc(size: u32) -> *mut u8 {
//!     let layout = std::alloc::Layout::from_size_align(size as usize, 1).unwrap();
//!     unsafe { std::alloc::alloc(layout) }
//! }
//! ```
//!
//! # Serialization Format
//!
//! Plugins communicate with the host via `MessagePack` serialization. The host
//! calls `process(ptr, len)` with a pointer to MessagePack-encoded [`PluginInput`].
//! The plugin returns a packed u64 containing a pointer and length to
//! MessagePack-encoded [`PluginOutput`].
//!
//! # Memory Management
//!
//! Plugins must export an `alloc(size: u32) -> *mut u8` function. The host uses
//! this to allocate memory in the WASM linear memory for passing input data.
//! The plugin uses it to allocate memory for output data.
//!
//! Optionally, plugins can export a `dealloc(ptr: *mut u8, size: u32)` function
//! to free memory. This is not required by the host but can be useful for
//! memory management within longer-running plugin operations.
//!
//! # Version Compatibility
//!
//! Plugin types are versioned with rustledger. For best compatibility, use the
//! same minor version of `rustledger-plugin-types` as the rustledger host you're
//! targeting (e.g., `0.10.x` for rustledger `0.10.x`).
//!
//! # Building
//!
//! Build your plugin for the WASM target:
//!
//! ```sh
//! rustup target add wasm32-unknown-unknown
//! cargo build --target wasm32-unknown-unknown --release
//! ```
//!
//! The output will be in `target/wasm32-unknown-unknown/release/your_plugin.wasm`

#![warn(missing_docs)]

use serde::{Deserialize, Serialize};

// ============================================================================
// Top-Level Plugin Interface
// ============================================================================

/// Input passed to a plugin.
///
/// The host serializes this struct via `MessagePack` and passes it to the
/// plugin's `process` function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginInput {
    /// All directives to process.
    pub directives: Vec<DirectiveWrapper>,
    /// Ledger options.
    pub options: PluginOptions,
    /// Plugin-specific configuration string (from the plugin directive).
    ///
    /// For example, `plugin "myplugin.wasm" "threshold=100"` would set
    /// `config` to `Some("threshold=100")`.
    pub config: Option<String>,
}

/// Output returned from a plugin.
///
/// The plugin serializes this struct via `MessagePack` and returns a pointer
/// to it from the `process` function.
///
/// Output is an **ordered sequence of operations** ([`PluginOp`]) — not a
/// replacement list of directives. The host materializes the resulting
/// directive list by walking the ops in order, preserving the original
/// source span / `file_id` for `Keep` and `Modify` ops so plugin-transformed
/// directives retain byte-precise source locations for error reporting.
///
/// Every input directive index must appear in EXACTLY ONE op across
/// `Keep` / `Modify` / `Delete`; the host validates this and emits a
/// plugin error if the invariant is violated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginOutput {
    /// Ordered operations that describe the resulting directive list.
    pub ops: Vec<PluginOp>,
    /// Errors generated by the plugin.
    pub errors: Vec<PluginError>,
}

impl PluginOutput {
    /// Create an output that passes through every input directive unchanged.
    /// `len` is the number of input directives.
    #[must_use]
    pub fn passthrough(len: usize) -> Self {
        Self {
            ops: (0..len).map(PluginOp::Keep).collect(),
            errors: Vec::new(),
        }
    }
}

/// One operation in a [`PluginOutput`]'s ordered op list.
///
/// Ops describe how each output directive relates to the input:
/// - [`PluginOp::Keep`] — reuse `input[i]` unchanged. Span and
///   `file_id` preserved.
/// - [`PluginOp::Modify`] — output a new wrapper, but inherit `input[i]`'s
///   source identity (span / `file_id`). Plugins use this when transforming
///   an existing directive's content (e.g., adding tags) so error
///   reporting still points at the original source location.
/// - [`PluginOp::Insert`] — emit a fresh directive with synthesized
///   source location (`SYNTHESIZED_FILE_ID`, zero span). Use for
///   directives the plugin invents from scratch.
/// - [`PluginOp::Delete`] — drop `input[i]`. Must be explicit; omitting
///   an index without `Delete` is a protocol violation that the host
///   reports as a plugin error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PluginOp {
    /// Reuse `input[i]` unchanged (preserves original span + `file_id`).
    Keep(usize),
    /// Replace `input[i]`'s content with `wrapper`, but inherit
    /// `input[i]`'s source identity (span + `file_id`).
    Modify(usize, DirectiveWrapper),
    /// Insert a fresh directive with synthesized source location.
    Insert(DirectiveWrapper),
    /// Drop `input[i]`. Must be explicit — see type-level docs.
    Delete(usize),
}

/// Ledger options passed to plugins.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PluginOptions {
    /// Operating currencies (from `option "operating_currency" "USD"`).
    pub operating_currencies: Vec<String>,
    /// Ledger title (from `option "title" "My Ledger"`).
    pub title: Option<String>,
}

// ============================================================================
// Plugin Errors
// ============================================================================

/// Error generated by a plugin.
///
/// Use [`PluginError::error`] or [`PluginError::warning`] to create errors,
/// and optionally chain [`PluginError::at`] to set the source location.
///
/// # Example
///
/// ```
/// use rustledger_plugin_types::{PluginError, PluginErrorSeverity};
///
/// let error = PluginError::error("Invalid transaction")
///     .at("ledger.beancount", 42);
///
/// let warning = PluginError::warning("Duplicate entry detected");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginError {
    /// Error message.
    pub message: String,
    /// Source file (if known).
    pub source_file: Option<String>,
    /// Line number (if known).
    pub line_number: Option<u32>,
    /// Error severity.
    pub severity: PluginErrorSeverity,
}

/// Severity of a plugin error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginErrorSeverity {
    /// Warning - processing continues.
    #[serde(rename = "warning")]
    Warning,
    /// Error - ledger is marked invalid.
    #[serde(rename = "error")]
    Error,
}

impl PluginError {
    /// Create a new error.
    #[must_use]
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            source_file: None,
            line_number: None,
            severity: PluginErrorSeverity::Error,
        }
    }

    /// Create a new warning.
    #[must_use]
    pub fn warning(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            source_file: None,
            line_number: None,
            severity: PluginErrorSeverity::Warning,
        }
    }

    /// Set the source location.
    #[must_use]
    pub fn at(mut self, file: impl Into<String>, line: u32) -> Self {
        self.source_file = Some(file.into());
        self.line_number = Some(line);
        self
    }
}

// ============================================================================
// Directive Types
// ============================================================================

/// A wrapper around directives for serialization.
///
/// This wrapper provides a uniform interface for all directive types,
/// with source location tracking for error reporting.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectiveWrapper {
    /// The type of directive (derived from data, not serialized to avoid duplicate keys).
    #[serde(skip_serializing, default)]
    pub directive_type: String,
    /// The directive date (YYYY-MM-DD format).
    pub date: String,
    /// Source filename (for tracking through plugin processing).
    /// If None, the directive was created by a plugin.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub filename: Option<String>,
    /// Source line number (1-based).
    /// If None, the directive was created by a plugin.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub lineno: Option<u32>,
    /// Directive-specific data as a nested structure.
    #[serde(flatten)]
    pub data: DirectiveData,
}

impl DirectiveWrapper {
    /// Returns the sort order for directive types, matching Python beancount's `SORT_ORDER`.
    ///
    /// Order ensures logical processing:
    /// - Open (-2): Accounts must be opened first
    /// - Balance (-1): Balance assertions checked before transactions
    /// - Default (0): Transactions, Commodity, Pad, Event, Note, Price, Query, Custom
    /// - Document (1): Documents recorded after transactions
    /// - Close (2): Accounts closed last
    #[must_use]
    pub const fn type_sort_order(&self) -> i8 {
        match &self.data {
            DirectiveData::Open(_) => -2,
            DirectiveData::Balance(_) => -1,
            DirectiveData::Document(_) => 1,
            DirectiveData::Close(_) => 2,
            _ => 0,
        }
    }

    /// Returns a sort key tuple matching Python beancount's `entry_sortkey()`.
    ///
    /// Sorts by: (date, `type_order`, lineno)
    #[must_use]
    pub fn sort_key(&self) -> (&str, i8, u32) {
        (
            &self.date,
            self.type_sort_order(),
            self.lineno.unwrap_or(u32::MAX),
        )
    }
}

/// Directive-specific data.
///
/// Each variant corresponds to a Beancount directive type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DirectiveData {
    /// Transaction data.
    #[serde(rename = "transaction")]
    Transaction(TransactionData),
    /// Balance assertion data.
    #[serde(rename = "balance")]
    Balance(BalanceData),
    /// Open account data.
    #[serde(rename = "open")]
    Open(OpenData),
    /// Close account data.
    #[serde(rename = "close")]
    Close(CloseData),
    /// Commodity declaration data.
    #[serde(rename = "commodity")]
    Commodity(CommodityData),
    /// Pad directive data.
    #[serde(rename = "pad")]
    Pad(PadData),
    /// Event data.
    #[serde(rename = "event")]
    Event(EventData),
    /// Note data.
    #[serde(rename = "note")]
    Note(NoteData),
    /// Document data.
    #[serde(rename = "document")]
    Document(DocumentData),
    /// Price data.
    #[serde(rename = "price")]
    Price(PriceData),
    /// Query data.
    #[serde(rename = "query")]
    Query(QueryData),
    /// Custom directive data.
    #[serde(rename = "custom")]
    Custom(CustomData),
}

// ============================================================================
// Transaction Types
// ============================================================================

/// Transaction data for serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionData {
    /// Transaction flag (`*` for complete, `!` for incomplete/pending).
    pub flag: String,
    /// Optional payee.
    pub payee: Option<String>,
    /// Narration/description.
    pub narration: String,
    /// Tags without the `#` prefix.
    pub tags: Vec<String>,
    /// Links without the `^` prefix.
    pub links: Vec<String>,
    /// Metadata key-value pairs.
    pub metadata: Vec<(String, MetaValueData)>,
    /// Postings.
    pub postings: Vec<PostingData>,
}

/// Posting data for serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostingData {
    /// Account name (e.g., `Assets:Bank:Checking`).
    pub account: String,
    /// Units (amount + currency). None for auto-balanced postings.
    pub units: Option<AmountData>,
    /// Cost specification (for lot tracking).
    pub cost: Option<CostData>,
    /// Price annotation (@ or @@).
    pub price: Option<PriceAnnotationData>,
    /// Optional posting flag.
    pub flag: Option<String>,
    /// Posting metadata.
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Amount data for serialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmountData {
    /// Number as string (preserves precision).
    pub number: String,
    /// Currency code.
    pub currency: String,
}

/// Cost data for serialization.
///
/// Represents cost specifications like `{100 USD}` or `{100 USD, 2024-01-01, "lot1"}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CostData {
    /// Per-unit cost number.
    pub number_per: Option<String>,
    /// Total cost number.
    pub number_total: Option<String>,
    /// Cost currency.
    pub currency: Option<String>,
    /// Acquisition date.
    pub date: Option<String>,
    /// Lot label.
    pub label: Option<String>,
    /// Merge lots flag.
    pub merge: bool,
}

/// Price annotation data.
///
/// Represents price annotations like `@ 100 USD` or `@@ 1000 USD`
/// (total price).
///
/// # Type-safe consumption (recommended)
///
/// Use [`PriceAnnotationData::view`] to get a [`PriceAnnotationView`]
/// — a typed enum that forces consumers to handle `Unit` and `Total`
/// arms exhaustively at compile time. **All new code that needs to
/// distinguish per-unit from total prices MUST use `view()`** rather
/// than reading `is_total` directly.
///
/// This struct is the wire format (kept for serialization stability
/// across the WASM plugin boundary). The `view()` enum is a shaped
/// accessor on top.
///
/// Pre-refactor (issue #992), the `implicit_prices` plugin read
/// `posting.price.amount` directly and silently ignored `is_total`,
/// emitting `@@` total amounts as per-unit prices. The fix in #997
/// added explicit handling, but the type system didn't catch the bug
/// originally because nothing forced consumers to read the bool. The
/// `view()` enum closes that loop: a missing match arm is a compile
/// error.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceAnnotationData {
    /// Whether this is a total price (`@@`) vs per-unit (`@`).
    ///
    /// **Prefer [`PriceAnnotationData::view`] for new code** — reading
    /// this field directly is the bug shape that produced #992
    /// (consumer ignores the field and treats every annotation as
    /// per-unit). The `view()` enum forces exhaustive handling at
    /// compile time.
    pub is_total: bool,
    /// The price amount (optional for incomplete/empty prices).
    pub amount: Option<AmountData>,
    /// The number only (for incomplete prices).
    pub number: Option<String>,
    /// The currency only (for incomplete prices).
    pub currency: Option<String>,
}

/// Typed view of a [`PriceAnnotationData`].
///
/// Each arm distinguishes per-unit (`@`) from total (`@@`) at the
/// **type level**, so a `match` on the view forces consumers to
/// handle both cases. This is the recommended way to consume price
/// annotations — see the docstring on [`PriceAnnotationData`] for the
/// motivating bug.
#[derive(Debug, Clone, Copy)]
pub enum PriceAnnotationView<'a> {
    /// `@ AMOUNT` — per-unit price with a complete amount.
    Unit(&'a AmountData),
    /// `@@ AMOUNT` — total price with a complete amount.
    ///
    /// Consumers that compute prices MUST divide by the posting's
    /// `units.number.abs()` to recover the per-unit price. See
    /// `rustledger_core::extract_per_unit_price` (in the
    /// `rustledger-core` crate; not linked because that crate is not a
    /// dependency of `rustledger-plugin-types`).
    Total(&'a AmountData),
    /// `@ NUMBER` / `@ CURRENCY` — per-unit annotation missing one
    /// or both of (number, currency).
    UnitIncomplete {
        /// The number, if present.
        number: Option<&'a str>,
        /// The currency, if present.
        currency: Option<&'a str>,
    },
    /// `@@ NUMBER` / `@@ CURRENCY` — incomplete total annotation.
    TotalIncomplete {
        /// The number, if present.
        number: Option<&'a str>,
        /// The currency, if present.
        currency: Option<&'a str>,
    },
}

impl PriceAnnotationData {
    /// Get a typed view that distinguishes per-unit from total at
    /// the type level. **Use this for new code that needs to handle
    /// the price differently based on `@` vs `@@`.**
    ///
    /// Returns one of four variants — a missing match arm at the
    /// consumer becomes a compile error, eliminating the class of
    /// bug that produced issue #992.
    #[must_use]
    pub fn view(&self) -> PriceAnnotationView<'_> {
        match (self.is_total, &self.amount) {
            (false, Some(a)) => PriceAnnotationView::Unit(a),
            (true, Some(a)) => PriceAnnotationView::Total(a),
            (false, None) => PriceAnnotationView::UnitIncomplete {
                number: self.number.as_deref(),
                currency: self.currency.as_deref(),
            },
            (true, None) => PriceAnnotationView::TotalIncomplete {
                number: self.number.as_deref(),
                currency: self.currency.as_deref(),
            },
        }
    }
}

// ============================================================================
// Metadata Types
// ============================================================================

/// Metadata value for serialization.
///
/// Metadata can hold various types of values, preserving type information
/// for accurate round-tripping.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum MetaValueData {
    /// String value.
    #[serde(rename = "string")]
    String(String),
    /// Number value (as string to preserve precision).
    #[serde(rename = "number")]
    Number(String),
    /// Date value (YYYY-MM-DD).
    #[serde(rename = "date")]
    Date(String),
    /// Account reference.
    #[serde(rename = "account")]
    Account(String),
    /// Currency reference.
    #[serde(rename = "currency")]
    Currency(String),
    /// Tag reference.
    #[serde(rename = "tag")]
    Tag(String),
    /// Link reference.
    #[serde(rename = "link")]
    Link(String),
    /// Amount value.
    #[serde(rename = "amount")]
    Amount(AmountData),
    /// Boolean value.
    #[serde(rename = "bool")]
    Bool(bool),
}

// ============================================================================
// Other Directive Types
// ============================================================================

/// Balance assertion data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceData {
    /// Account name.
    pub account: String,
    /// Expected balance.
    pub amount: AmountData,
    /// Tolerance for balance check.
    pub tolerance: Option<String>,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Open account data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenData {
    /// Account name.
    pub account: String,
    /// Allowed currencies (empty means any currency).
    pub currencies: Vec<String>,
    /// Booking method (FIFO, LIFO, etc.).
    pub booking: Option<String>,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Close account data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloseData {
    /// Account name.
    pub account: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Commodity declaration data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommodityData {
    /// Currency code.
    pub currency: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Pad directive data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PadData {
    /// Account to pad.
    pub account: String,
    /// Source account for padding.
    pub source_account: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Event data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventData {
    /// Event type.
    pub event_type: String,
    /// Event value.
    pub value: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Note data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteData {
    /// Account name.
    pub account: String,
    /// Note comment.
    pub comment: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Document data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentData {
    /// Account name.
    pub account: String,
    /// Document path.
    pub path: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Price directive data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriceData {
    /// Currency being priced.
    pub currency: String,
    /// Price amount.
    pub amount: AmountData,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Query directive data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryData {
    /// Query name.
    pub name: String,
    /// Query string (BQL).
    pub query: String,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

/// Custom directive data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomData {
    /// Custom type (first value after `custom` keyword).
    pub custom_type: String,
    /// Values preserving their types.
    pub values: Vec<MetaValueData>,
    /// Metadata key-value pairs.
    #[serde(default)]
    pub metadata: Vec<(String, MetaValueData)>,
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Sort directives using beancount's standard ordering.
///
/// This matches Python beancount's `entry_sortkey()`:
/// 1. Primary: date
/// 2. Secondary: directive type (Open, Balance, default, Document, Close)
/// 3. Tertiary: line number (preserves file order for same-date, same-type entries)
pub fn sort_directives(directives: &mut [DirectiveWrapper]) {
    directives.sort_by(|a, b| a.sort_key().cmp(&b.sort_key()));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_plugin_error_builder() {
        let error = PluginError::error("test error").at("file.beancount", 10);
        assert_eq!(error.message, "test error");
        assert_eq!(error.source_file, Some("file.beancount".to_string()));
        assert_eq!(error.line_number, Some(10));
        assert_eq!(error.severity, PluginErrorSeverity::Error);
    }

    #[test]
    fn test_plugin_warning() {
        let warning = PluginError::warning("test warning");
        assert_eq!(warning.severity, PluginErrorSeverity::Warning);
    }

    #[test]
    fn test_directive_sort_order() {
        let open = DirectiveWrapper {
            directive_type: String::new(),
            date: "2024-01-01".to_string(),
            filename: None,
            lineno: Some(1),
            data: DirectiveData::Open(OpenData {
                account: "Assets:Bank".to_string(),
                currencies: vec![],
                booking: None,
                metadata: vec![],
            }),
        };
        assert_eq!(open.type_sort_order(), -2);

        let close = DirectiveWrapper {
            directive_type: String::new(),
            date: "2024-01-01".to_string(),
            filename: None,
            lineno: Some(2),
            data: DirectiveData::Close(CloseData {
                account: "Assets:Bank".to_string(),
                metadata: vec![],
            }),
        };
        assert_eq!(close.type_sort_order(), 2);
    }

    #[test]
    fn test_serde_roundtrip() {
        let input = PluginInput {
            directives: vec![DirectiveWrapper {
                directive_type: String::new(),
                date: "2024-01-15".to_string(),
                filename: Some("test.beancount".to_string()),
                lineno: Some(42),
                data: DirectiveData::Transaction(TransactionData {
                    flag: "*".to_string(),
                    payee: Some("Coffee Shop".to_string()),
                    narration: "Morning coffee".to_string(),
                    tags: vec!["food".to_string()],
                    links: vec![],
                    metadata: vec![],
                    postings: vec![PostingData {
                        account: "Expenses:Food".to_string(),
                        units: Some(AmountData {
                            number: "5.00".to_string(),
                            currency: "USD".to_string(),
                        }),
                        cost: None,
                        price: None,
                        flag: None,
                        metadata: vec![],
                    }],
                }),
            }],
            options: PluginOptions {
                operating_currencies: vec!["USD".to_string()],
                title: Some("Test Ledger".to_string()),
            },
            config: Some("threshold=100".to_string()),
        };

        // Test JSON roundtrip
        let json = serde_json::to_string(&input).unwrap();
        let decoded: PluginInput = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.directives.len(), 1);
        assert_eq!(decoded.config, Some("threshold=100".to_string()));

        // Test MessagePack roundtrip
        let msgpack = rmp_serde::to_vec(&input).unwrap();
        let decoded: PluginInput = rmp_serde::from_slice(&msgpack).unwrap();
        assert_eq!(decoded.directives.len(), 1);
    }

    // ===== PriceAnnotationData::view() — all four arms =====
    //
    // The view() enum is the type-safe interface that prevents the
    // #992 bug shape (consumer ignoring the is_total discriminator).
    // These tests pin the mapping from (is_total, amount) to each
    // PriceAnnotationView variant so a refactor of the underlying
    // struct can't silently change the dispatch.

    fn amount(number: &str, currency: &str) -> AmountData {
        AmountData {
            number: number.to_string(),
            currency: currency.to_string(),
        }
    }

    #[test]
    fn view_unit_complete() {
        // `@ 1.40 EUR`
        let pad = PriceAnnotationData {
            is_total: false,
            amount: Some(amount("1.40", "EUR")),
            number: None,
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::Unit(a) => {
                assert_eq!(a.number, "1.40");
                assert_eq!(a.currency, "EUR");
            }
            other => panic!("expected Unit, got {other:?}"),
        }
    }

    #[test]
    fn view_total_complete() {
        // `@@ 1500 USD`
        let pad = PriceAnnotationData {
            is_total: true,
            amount: Some(amount("1500", "USD")),
            number: None,
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::Total(a) => {
                assert_eq!(a.number, "1500");
                assert_eq!(a.currency, "USD");
            }
            other => panic!("expected Total, got {other:?}"),
        }
    }

    #[test]
    fn view_unit_incomplete_number_only() {
        // `@ 1.40` — number but no currency
        let pad = PriceAnnotationData {
            is_total: false,
            amount: None,
            number: Some("1.40".to_string()),
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::UnitIncomplete { number, currency } => {
                assert_eq!(number, Some("1.40"));
                assert_eq!(currency, None);
            }
            other => panic!("expected UnitIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_unit_incomplete_currency_only() {
        // `@ EUR` — currency but no number
        let pad = PriceAnnotationData {
            is_total: false,
            amount: None,
            number: None,
            currency: Some("EUR".to_string()),
        };
        match pad.view() {
            PriceAnnotationView::UnitIncomplete { number, currency } => {
                assert_eq!(number, None);
                assert_eq!(currency, Some("EUR"));
            }
            other => panic!("expected UnitIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_unit_incomplete_neither() {
        // `@` — bare annotation, neither number nor currency
        let pad = PriceAnnotationData {
            is_total: false,
            amount: None,
            number: None,
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::UnitIncomplete { number, currency } => {
                assert_eq!(number, None);
                assert_eq!(currency, None);
            }
            other => panic!("expected UnitIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_total_incomplete_number_only() {
        // `@@ 1500`
        let pad = PriceAnnotationData {
            is_total: true,
            amount: None,
            number: Some("1500".to_string()),
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::TotalIncomplete { number, currency } => {
                assert_eq!(number, Some("1500"));
                assert_eq!(currency, None);
            }
            other => panic!("expected TotalIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_total_incomplete_currency_only() {
        // `@@ USD`
        let pad = PriceAnnotationData {
            is_total: true,
            amount: None,
            number: None,
            currency: Some("USD".to_string()),
        };
        match pad.view() {
            PriceAnnotationView::TotalIncomplete { number, currency } => {
                assert_eq!(number, None);
                assert_eq!(currency, Some("USD"));
            }
            other => panic!("expected TotalIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_total_incomplete_neither() {
        // `@@` — bare total annotation
        let pad = PriceAnnotationData {
            is_total: true,
            amount: None,
            number: None,
            currency: None,
        };
        match pad.view() {
            PriceAnnotationView::TotalIncomplete { number, currency } => {
                assert_eq!(number, None);
                assert_eq!(currency, None);
            }
            other => panic!("expected TotalIncomplete, got {other:?}"),
        }
    }

    #[test]
    fn view_amount_present_takes_priority_over_number_currency_fields() {
        // If both `amount` AND the loose `number`/`currency` fields
        // are set, `amount` wins — view() returns Unit/Total, never
        // an Incomplete variant. This pins the precedence so a
        // future field-juggling refactor can't accidentally invert
        // it.
        let pad = PriceAnnotationData {
            is_total: false,
            amount: Some(amount("1.40", "EUR")),
            number: Some("99".to_string()),    // ignored
            currency: Some("XYZ".to_string()), // ignored
        };
        match pad.view() {
            PriceAnnotationView::Unit(a) => {
                assert_eq!(a.number, "1.40");
                assert_eq!(a.currency, "EUR");
            }
            other => panic!("expected Unit, got {other:?}"),
        }
    }
}