openpit 0.8.1

Embeddable pre-trade risk SDK
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
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://openpit.dev and the OWNERS file for details.

use std::fmt::{Display, Formatter};

/// Reject scope returned by policies.
///
/// # Examples
///
/// ```
/// use openpit::pretrade::RejectScope;
///
/// let scope = RejectScope::Order;
/// match scope {
///     RejectScope::Order => { /* retry is safe; engine remains operational */ }
///     RejectScope::Account => { /* halt trading until situation is resolved */ }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RejectScope {
    /// Reject only the current request.
    Order,
    /// Account-level reject signal.
    ///
    /// Only the pre-trade stages derive an account block from this scope.
    /// [`crate::Engine::start_pre_trade`] and
    /// [`crate::Engine::execute_pre_trade`] record the start-stage block.
    /// [`crate::pretrade::PreTradeRequest::execute`] records the main-stage
    /// block.
    ///
    /// The public dry-run entry points
    /// [`crate::Engine::start_pre_trade_dry_run`] and
    /// [`crate::Engine::execute_pre_trade_dry_run`] report the block a real
    /// call would record, but do not record it.
    ///
    /// [`crate::Engine::apply_account_adjustment`] and
    /// [`crate::Engine::apply_execution_report`] never read this scope.
    /// Blocking on those paths is independent of this value.
    ///
    /// A block derived here stays latched until `Accounts::unblock` clears that
    /// account. Retry, replay, and time passing do not clear it.
    ///
    /// A policy that intends to reject only the current request without
    /// latching a block on the account must return [`RejectScope::Order`].
    Account,
}

/// Standardized reject code for blocked orders.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RejectCode {
    /// A mandatory order field was not provided.
    MissingRequiredField,
    /// A field format is syntactically invalid.
    InvalidFieldFormat,
    /// A field value is outside accepted domain values.
    InvalidFieldValue,
    /// The order type is not supported.
    UnsupportedOrderType,
    /// The time-in-force value is not supported.
    UnsupportedTimeInForce,
    /// A requested order attribute is unsupported.
    UnsupportedOrderAttribute,
    /// Client order ID is already in use.
    DuplicateClientOrderId,
    /// Order arrival is outside the allowed entry window.
    TooLateToEnter,
    /// Venue session is closed for trading.
    ExchangeClosed,
    /// Instrument identifier is not recognized.
    UnknownInstrument,
    /// Account identifier is not recognized.
    UnknownAccount,
    /// Venue identifier is not recognized.
    UnknownVenue,
    /// Clearing account is not recognized.
    UnknownClearingAccount,
    /// Collateral asset is not recognized.
    UnknownCollateralAsset,
    /// Available cash is not sufficient for this order.
    InsufficientFunds,
    /// Margin is insufficient for this order.
    InsufficientMargin,
    /// Position inventory is insufficient for this order.
    InsufficientPosition,
    /// Credit limit is exceeded.
    CreditLimitExceeded,
    /// A generic risk limit is exceeded.
    RiskLimitExceeded,
    /// Multiple size limits are exceeded by one order.
    OrderExceedsLimit,
    /// Quantity limit is exceeded.
    OrderQtyExceedsLimit,
    /// Notional limit is exceeded.
    OrderNotionalExceedsLimit,
    /// Position limit is exceeded.
    PositionLimitExceeded,
    /// Concentration limit is exceeded.
    ConcentrationLimitExceeded,
    /// Leverage limit is exceeded.
    LeverageLimitExceeded,
    /// Rate limit for order submissions is exceeded.
    RateLimitExceeded,
    /// PnL-based kill switch is currently triggered.
    PnlKillSwitchTriggered,
    /// Account is blocked from trading.
    AccountBlocked,
    /// Account is not authorized to place this order.
    AccountNotAuthorized,
    /// Compliance rule forbids this order.
    ComplianceRestriction,
    /// Instrument is restricted for this account or venue.
    InstrumentRestricted,
    /// Jurisdictional restriction forbids this order.
    JurisdictionRestriction,
    /// Wash-trade prevention blocked this order.
    WashTradePrevention,
    /// Self-match prevention blocked this order.
    SelfMatchPrevention,
    /// Short-sale restriction blocked this order.
    ShortSaleRestriction,
    /// Required risk configuration is missing.
    RiskConfigurationMissing,
    /// Required reference data is unavailable.
    ReferenceDataUnavailable,
    /// Order value could not be calculated.
    OrderValueCalculationFailed,
    /// Risk system is temporarily unavailable.
    SystemUnavailable,
    /// Mark price required for order evaluation is unavailable.
    MarkPriceUnavailable,
    /// Account adjustment would violate its configured bounds.
    AccountAdjustmentBoundsExceeded,
    /// Underlying decimal arithmetic overflowed during evaluation.
    ///
    /// Distinct from [`Self::OrderValueCalculationFailed`]: that code
    /// signals that an order value could not be produced for any
    /// reason (missing input, invalid result, division by zero),
    /// while this code is reserved for the specific case where a
    /// `checked_add`/`checked_sub`/`checked_mul` exceeded the value
    /// range of the underlying decimal representation.
    ArithmeticOverflow,
    /// Reserved discriminant for caller-defined reject classes.
    ///
    /// Use together with `Reject::with_user_data` to attach a caller-defined
    /// payload that the receiving code can decode. The SDK does not interpret
    /// this code beyond mapping it to FFI value 254.
    Custom, // FFI: reserved as 254
    /// Reject reason does not fit a more specific code.
    Other,
}

impl RejectCode {
    /// Returns whether this code means that a policy could not determine or
    /// apply the effect of a historical order.
    ///
    /// [`Engine::apply_drop_copy`](crate::Engine::apply_drop_copy) treats an
    /// evaluation failure as an atomic error. All other codes are ordinary
    /// policy verdicts: they do not prevent drop-copy from recording an order
    /// that already happened.
    ///
    /// The classification is exhaustive:
    ///
    /// - [`MissingRequiredField`](Self::MissingRequiredField) is an evaluation
    ///   failure because a policy-required input is absent.
    /// - [`UnknownInstrument`](Self::UnknownInstrument),
    ///   [`UnknownAccount`](Self::UnknownAccount),
    ///   [`UnknownVenue`](Self::UnknownVenue),
    ///   [`UnknownClearingAccount`](Self::UnknownClearingAccount), and
    ///   [`UnknownCollateralAsset`](Self::UnknownCollateralAsset) are
    ///   evaluation failures because a required domain entity cannot be
    ///   resolved.
    /// - [`RiskConfigurationMissing`](Self::RiskConfigurationMissing),
    ///   [`ReferenceDataUnavailable`](Self::ReferenceDataUnavailable),
    ///   [`OrderValueCalculationFailed`](Self::OrderValueCalculationFailed),
    ///   [`SystemUnavailable`](Self::SystemUnavailable),
    ///   [`MarkPriceUnavailable`](Self::MarkPriceUnavailable), and
    ///   [`ArithmeticOverflow`](Self::ArithmeticOverflow) are evaluation
    ///   failures because required configuration, data, computation, service,
    ///   price, or representable arithmetic result is unavailable.
    /// - [`InvalidFieldFormat`](Self::InvalidFieldFormat) and
    ///   [`InvalidFieldValue`](Self::InvalidFieldValue) are ordinary verdicts:
    ///   the policy inspected the supplied value and classified it.
    /// - [`UnsupportedOrderType`](Self::UnsupportedOrderType),
    ///   [`UnsupportedTimeInForce`](Self::UnsupportedTimeInForce), and
    ///   [`UnsupportedOrderAttribute`](Self::UnsupportedOrderAttribute) are
    ///   ordinary verdicts about understood but unsupported semantics.
    /// - [`DuplicateClientOrderId`](Self::DuplicateClientOrderId),
    ///   [`TooLateToEnter`](Self::TooLateToEnter), and
    ///   [`ExchangeClosed`](Self::ExchangeClosed) are ordinary admission
    ///   verdicts that do not prevent historical bookkeeping.
    /// - [`InsufficientFunds`](Self::InsufficientFunds),
    ///   [`InsufficientMargin`](Self::InsufficientMargin),
    ///   [`InsufficientPosition`](Self::InsufficientPosition),
    ///   [`CreditLimitExceeded`](Self::CreditLimitExceeded),
    ///   [`RiskLimitExceeded`](Self::RiskLimitExceeded),
    ///   [`OrderExceedsLimit`](Self::OrderExceedsLimit),
    ///   [`OrderQtyExceedsLimit`](Self::OrderQtyExceedsLimit),
    ///   [`OrderNotionalExceedsLimit`](Self::OrderNotionalExceedsLimit),
    ///   [`PositionLimitExceeded`](Self::PositionLimitExceeded),
    ///   [`ConcentrationLimitExceeded`](Self::ConcentrationLimitExceeded),
    ///   [`LeverageLimitExceeded`](Self::LeverageLimitExceeded), and
    ///   [`RateLimitExceeded`](Self::RateLimitExceeded) are ordinary risk
    ///   verdicts produced after evaluating the order.
    /// - [`PnlKillSwitchTriggered`](Self::PnlKillSwitchTriggered) and
    ///   [`AccountBlocked`](Self::AccountBlocked) are ordinary control
    ///   verdicts. Drop-copy may still apply bookkeeping and publish a block.
    /// - [`AccountNotAuthorized`](Self::AccountNotAuthorized),
    ///   [`ComplianceRestriction`](Self::ComplianceRestriction),
    ///   [`InstrumentRestricted`](Self::InstrumentRestricted),
    ///   [`JurisdictionRestriction`](Self::JurisdictionRestriction),
    ///   [`WashTradePrevention`](Self::WashTradePrevention),
    ///   [`SelfMatchPrevention`](Self::SelfMatchPrevention), and
    ///   [`ShortSaleRestriction`](Self::ShortSaleRestriction) are ordinary
    ///   authorization or compliance verdicts.
    /// - [`AccountAdjustmentBoundsExceeded`](Self::AccountAdjustmentBoundsExceeded)
    ///   is an ordinary account-adjustment verdict, not failure to evaluate a
    ///   drop-copy order.
    /// - [`Custom`](Self::Custom) is ordinary because the SDK cannot infer its
    ///   caller-defined semantics. A custom policy that must abort drop-copy
    ///   should use a standardized evaluation-failure code.
    /// - [`Other`](Self::Other) is an ordinary fallback with no
    ///   evaluation-failure semantics.
    pub const fn is_evaluation_failure(self) -> bool {
        match self {
            Self::MissingRequiredField
            | Self::UnknownInstrument
            | Self::UnknownAccount
            | Self::UnknownVenue
            | Self::UnknownClearingAccount
            | Self::UnknownCollateralAsset
            | Self::RiskConfigurationMissing
            | Self::ReferenceDataUnavailable
            | Self::OrderValueCalculationFailed
            | Self::SystemUnavailable
            | Self::MarkPriceUnavailable
            | Self::ArithmeticOverflow => true,
            Self::InvalidFieldFormat
            | Self::InvalidFieldValue
            | Self::UnsupportedOrderType
            | Self::UnsupportedTimeInForce
            | Self::UnsupportedOrderAttribute
            | Self::DuplicateClientOrderId
            | Self::TooLateToEnter
            | Self::ExchangeClosed
            | Self::InsufficientFunds
            | Self::InsufficientMargin
            | Self::InsufficientPosition
            | Self::CreditLimitExceeded
            | Self::RiskLimitExceeded
            | Self::OrderExceedsLimit
            | Self::OrderQtyExceedsLimit
            | Self::OrderNotionalExceedsLimit
            | Self::PositionLimitExceeded
            | Self::ConcentrationLimitExceeded
            | Self::LeverageLimitExceeded
            | Self::RateLimitExceeded
            | Self::PnlKillSwitchTriggered
            | Self::AccountBlocked
            | Self::AccountNotAuthorized
            | Self::ComplianceRestriction
            | Self::InstrumentRestricted
            | Self::JurisdictionRestriction
            | Self::WashTradePrevention
            | Self::SelfMatchPrevention
            | Self::ShortSaleRestriction
            | Self::AccountAdjustmentBoundsExceeded
            | Self::Custom
            | Self::Other => false,
        }
    }

    /// Returns the stable string representation of this code.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingRequiredField => "MissingRequiredField",
            Self::InvalidFieldFormat => "InvalidFieldFormat",
            Self::InvalidFieldValue => "InvalidFieldValue",
            Self::UnsupportedOrderType => "UnsupportedOrderType",
            Self::UnsupportedTimeInForce => "UnsupportedTimeInForce",
            Self::UnsupportedOrderAttribute => "UnsupportedOrderAttribute",
            Self::DuplicateClientOrderId => "DuplicateClientOrderId",
            Self::TooLateToEnter => "TooLateToEnter",
            Self::ExchangeClosed => "ExchangeClosed",
            Self::UnknownInstrument => "UnknownInstrument",
            Self::UnknownAccount => "UnknownAccount",
            Self::UnknownVenue => "UnknownVenue",
            Self::UnknownClearingAccount => "UnknownClearingAccount",
            Self::UnknownCollateralAsset => "UnknownCollateralAsset",
            Self::InsufficientFunds => "InsufficientFunds",
            Self::InsufficientMargin => "InsufficientMargin",
            Self::InsufficientPosition => "InsufficientPosition",
            Self::CreditLimitExceeded => "CreditLimitExceeded",
            Self::RiskLimitExceeded => "RiskLimitExceeded",
            Self::OrderExceedsLimit => "OrderExceedsLimit",
            Self::OrderQtyExceedsLimit => "OrderQtyExceedsLimit",
            Self::OrderNotionalExceedsLimit => "OrderNotionalExceedsLimit",
            Self::PositionLimitExceeded => "PositionLimitExceeded",
            Self::ConcentrationLimitExceeded => "ConcentrationLimitExceeded",
            Self::LeverageLimitExceeded => "LeverageLimitExceeded",
            Self::RateLimitExceeded => "RateLimitExceeded",
            Self::PnlKillSwitchTriggered => "PnlKillSwitchTriggered",
            Self::AccountBlocked => "AccountBlocked",
            Self::AccountNotAuthorized => "AccountNotAuthorized",
            Self::ComplianceRestriction => "ComplianceRestriction",
            Self::InstrumentRestricted => "InstrumentRestricted",
            Self::JurisdictionRestriction => "JurisdictionRestriction",
            Self::WashTradePrevention => "WashTradePrevention",
            Self::SelfMatchPrevention => "SelfMatchPrevention",
            Self::ShortSaleRestriction => "ShortSaleRestriction",
            Self::RiskConfigurationMissing => "RiskConfigurationMissing",
            Self::ReferenceDataUnavailable => "ReferenceDataUnavailable",
            Self::OrderValueCalculationFailed => "OrderValueCalculationFailed",
            Self::SystemUnavailable => "SystemUnavailable",
            Self::MarkPriceUnavailable => "MarkPriceUnavailable",
            Self::AccountAdjustmentBoundsExceeded => "AccountAdjustmentBoundsExceeded",
            Self::ArithmeticOverflow => "ArithmeticOverflow",
            Self::Custom => "Custom",
            Self::Other => "Other",
        }
    }
}

impl Display for RejectCode {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Single rejection record returned by checks.
///
/// # Examples
///
/// ```
/// use openpit::pretrade::{Reject, RejectCode, RejectScope};
///
/// let reject = Reject::new(
///     "RateLimitPolicy",
///     RejectScope::Order,
///     RejectCode::RateLimitExceeded,
///     "rate limit exceeded",
///     "submitted 3 orders in 1s window, max allowed: 2",
/// );
/// assert_eq!(reject.code, RejectCode::RateLimitExceeded);
/// assert_eq!(reject.reason, "rate limit exceeded");
/// assert_eq!(reject.details, "submitted 3 orders in 1s window, max allowed: 2");
/// assert_eq!(reject.policy, "RateLimitPolicy");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reject {
    /// Human-readable reject reason.
    pub reason: String,
    /// Case-specific reject details.
    pub details: String,
    /// Policy name that produced the reject.
    pub policy: String,
    /// Opaque caller-defined token.
    ///
    /// The SDK never inspects, dereferences, or frees this value. Its meaning,
    /// lifetime, and thread-safety are the caller's responsibility. `0` / null
    /// means "not set". See the project Threading Contract for the full lifetime
    /// model.
    ///
    /// The token flows through every reject path the SDK exposes (start-stage,
    /// main-stage, account-adjustment, batch results) and is preserved on
    /// `Clone`.
    pub user_data: usize,
    /// Stable machine-readable reject code.
    pub code: RejectCode,
    /// Reject scope.
    pub scope: RejectScope,
}

impl Display for Reject {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "[{}] {}: {}",
            self.policy, self.reason, self.details
        )
    }
}

impl std::error::Error for Reject {}

/// Collection of rejects returned by [`PreTradeRequest::execute`].
///
/// Implements `Deref` to `[Reject]` for direct element access. Equality
/// compares only the reject list and deliberately ignores the attached policy
/// result, which is auxiliary drop-copy output rather than part of the verdict.
///
/// [`PreTradeRequest::execute`]: crate::pretrade::PreTradeRequest::execute
#[derive(Clone, Debug)]
pub struct Rejects {
    rejects: Vec<Reject>,
    policy_result: Option<Box<super::PolicyPreTradeResult>>,
}

impl PartialEq for Rejects {
    fn eq(&self, other: &Self) -> bool {
        self.rejects == other.rejects
    }
}

impl Eq for Rejects {}

impl Rejects {
    /// Creates a reject collection from a vector.
    pub fn new(rejects: Vec<Reject>) -> Self {
        Self {
            rejects,
            policy_result: None,
        }
    }

    /// Attaches the policy output computed before these rejects were produced.
    ///
    /// Drop-copy consumes this output when the rejects are non-enforcing.
    /// Ordinary pre-trade paths continue to ignore it.
    #[doc(hidden)]
    pub fn with_policy_result(mut self, result: super::PolicyPreTradeResult) -> Self {
        self.policy_result = Some(Box::new(result));
        self
    }

    pub(crate) fn into_vec(self) -> Vec<Reject> {
        self.rejects
    }

    pub(crate) fn into_parts(self) -> (Vec<Reject>, Option<super::PolicyPreTradeResult>) {
        (self.rejects, self.policy_result.map(|result| *result))
    }
}

impl From<Reject> for Rejects {
    fn from(value: Reject) -> Self {
        Self::new(vec![value])
    }
}

impl From<Vec<Reject>> for Rejects {
    fn from(value: Vec<Reject>) -> Self {
        Self::new(value)
    }
}

impl std::ops::Deref for Rejects {
    type Target = Vec<Reject>;
    fn deref(&self) -> &Self::Target {
        &self.rejects
    }
}

impl Display for Rejects {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        for (i, reject) in self.rejects.iter().enumerate() {
            if i > 0 {
                write!(formatter, "; ")?;
            }
            Display::fmt(reject, formatter)?;
        }
        Ok(())
    }
}

impl std::error::Error for Rejects {}

/// Account-level reject record produced by policies.
///
/// Carries the same fields as [`Reject`] except scope, which is fixed to
/// [`RejectScope::Account`] on conversion. Use [`From<AccountBlock> for
/// Reject`] to obtain a full reject record.
///
/// # Examples
///
/// ```
/// use openpit::pretrade::{AccountBlock, Reject, RejectCode, RejectScope};
///
/// let block = AccountBlock::new(
///     "PnlKillSwitch",
///     RejectCode::PnlKillSwitchTriggered,
///     "daily loss limit breached",
///     "loss exceeded configured threshold",
/// );
/// let reject = Reject::from(block);
/// assert_eq!(reject.scope, RejectScope::Account);
/// assert_eq!(reject.code, RejectCode::PnlKillSwitchTriggered);
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct AccountBlock {
    /// Human-readable reject reason.
    pub reason: String,
    /// Case-specific reject details.
    pub details: String,
    /// Policy name that produced the block.
    pub policy: String,
    /// Opaque caller-defined token.
    ///
    /// The SDK never inspects, dereferences, or frees this value. Its meaning,
    /// lifetime, and thread-safety are the caller's responsibility. `0` / null
    /// means "not set". See the project Threading Contract for the full lifetime
    /// model.
    pub user_data: usize,
    /// Stable machine-readable reject code.
    pub code: RejectCode,
    /// Engine-owned provenance for a block produced from a provisional
    /// account-PnL assertion. It is deliberately absent from every public
    /// binding and constructor.
    pub(crate) provenance: Option<u64>,
}

impl PartialEq for AccountBlock {
    fn eq(&self, other: &Self) -> bool {
        self.reason == other.reason
            && self.details == other.details
            && self.policy == other.policy
            && self.user_data == other.user_data
            && self.code == other.code
    }
}

impl Eq for AccountBlock {}

impl AccountBlock {
    /// Creates an account block with human-readable reason and details.
    pub fn new(
        policy: impl Into<String>,
        code: RejectCode,
        reason: impl Into<String>,
        details: impl Into<String>,
    ) -> Self {
        Self {
            code,
            reason: reason.into(),
            details: details.into(),
            policy: policy.into(),
            user_data: 0,
            provenance: None,
        }
    }

    /// Returns a copy of this block with caller-defined opaque token.
    pub fn with_user_data(mut self, user_data: usize) -> Self {
        self.user_data = user_data;
        self
    }

    pub(crate) fn with_provenance(mut self, provenance: Option<u64>) -> Self {
        self.provenance = provenance;
        self
    }

    pub(crate) fn provenance(&self) -> Option<u64> {
        self.provenance
    }
}

impl From<AccountBlock> for Reject {
    fn from(block: AccountBlock) -> Self {
        Self {
            reason: block.reason,
            details: block.details,
            policy: block.policy,
            user_data: block.user_data,
            code: block.code,
            scope: RejectScope::Account,
        }
    }
}

impl Reject {
    /// Creates a reject with human-readable reason and details.
    pub fn new(
        policy: impl Into<String>,
        scope: RejectScope,
        code: RejectCode,
        reason: impl Into<String>,
        details: impl Into<String>,
    ) -> Self {
        Self {
            code,
            reason: reason.into(),
            details: details.into(),
            policy: policy.into(),
            user_data: 0,
            scope,
        }
    }

    /// Returns a copy of this reject with caller-defined opaque token.
    pub fn with_user_data(mut self, user_data: usize) -> Self {
        self.user_data = user_data;
        self
    }

    /// Creates an [`AccountBlock`] from this reject, substituting `code` for
    /// the original reject code. All other fields are copied verbatim.
    pub fn account_block_with_code(&self, code: RejectCode) -> AccountBlock {
        AccountBlock::new(&self.policy, code, &self.reason, &self.details)
            .with_user_data(self.user_data)
    }
}

#[cfg(test)]
mod tests {
    use super::{AccountBlock, RejectCode};

    #[test]
    fn account_block_equality_ignores_engine_provenance() {
        let visible = AccountBlock::new("Policy", RejectCode::Other, "reason", "details");
        let provisional = visible.clone().with_provenance(Some(42));

        assert_eq!(visible, provisional);
    }

    #[test]
    fn reject_code_as_str_and_display_are_stable_for_all_values() {
        let cases = [
            (RejectCode::MissingRequiredField, "MissingRequiredField"),
            (RejectCode::InvalidFieldFormat, "InvalidFieldFormat"),
            (RejectCode::InvalidFieldValue, "InvalidFieldValue"),
            (RejectCode::UnsupportedOrderType, "UnsupportedOrderType"),
            (RejectCode::UnsupportedTimeInForce, "UnsupportedTimeInForce"),
            (
                RejectCode::UnsupportedOrderAttribute,
                "UnsupportedOrderAttribute",
            ),
            (RejectCode::DuplicateClientOrderId, "DuplicateClientOrderId"),
            (RejectCode::TooLateToEnter, "TooLateToEnter"),
            (RejectCode::ExchangeClosed, "ExchangeClosed"),
            (RejectCode::UnknownInstrument, "UnknownInstrument"),
            (RejectCode::UnknownAccount, "UnknownAccount"),
            (RejectCode::UnknownVenue, "UnknownVenue"),
            (RejectCode::UnknownClearingAccount, "UnknownClearingAccount"),
            (RejectCode::UnknownCollateralAsset, "UnknownCollateralAsset"),
            (RejectCode::InsufficientFunds, "InsufficientFunds"),
            (RejectCode::InsufficientMargin, "InsufficientMargin"),
            (RejectCode::InsufficientPosition, "InsufficientPosition"),
            (RejectCode::CreditLimitExceeded, "CreditLimitExceeded"),
            (RejectCode::RiskLimitExceeded, "RiskLimitExceeded"),
            (RejectCode::OrderExceedsLimit, "OrderExceedsLimit"),
            (RejectCode::OrderQtyExceedsLimit, "OrderQtyExceedsLimit"),
            (
                RejectCode::OrderNotionalExceedsLimit,
                "OrderNotionalExceedsLimit",
            ),
            (RejectCode::PositionLimitExceeded, "PositionLimitExceeded"),
            (
                RejectCode::ConcentrationLimitExceeded,
                "ConcentrationLimitExceeded",
            ),
            (RejectCode::LeverageLimitExceeded, "LeverageLimitExceeded"),
            (RejectCode::RateLimitExceeded, "RateLimitExceeded"),
            (RejectCode::PnlKillSwitchTriggered, "PnlKillSwitchTriggered"),
            (RejectCode::AccountBlocked, "AccountBlocked"),
            (RejectCode::AccountNotAuthorized, "AccountNotAuthorized"),
            (RejectCode::ComplianceRestriction, "ComplianceRestriction"),
            (RejectCode::InstrumentRestricted, "InstrumentRestricted"),
            (
                RejectCode::JurisdictionRestriction,
                "JurisdictionRestriction",
            ),
            (RejectCode::WashTradePrevention, "WashTradePrevention"),
            (RejectCode::SelfMatchPrevention, "SelfMatchPrevention"),
            (RejectCode::ShortSaleRestriction, "ShortSaleRestriction"),
            (
                RejectCode::RiskConfigurationMissing,
                "RiskConfigurationMissing",
            ),
            (
                RejectCode::ReferenceDataUnavailable,
                "ReferenceDataUnavailable",
            ),
            (
                RejectCode::OrderValueCalculationFailed,
                "OrderValueCalculationFailed",
            ),
            (RejectCode::SystemUnavailable, "SystemUnavailable"),
            (RejectCode::MarkPriceUnavailable, "MarkPriceUnavailable"),
            (
                RejectCode::AccountAdjustmentBoundsExceeded,
                "AccountAdjustmentBoundsExceeded",
            ),
            (RejectCode::ArithmeticOverflow, "ArithmeticOverflow"),
            (RejectCode::Custom, "Custom"),
            (RejectCode::Other, "Other"),
        ];

        for (code, expected_name) in cases {
            assert_eq!(code.as_str(), expected_name);
            assert_eq!(code.to_string(), expected_name);
        }
    }

    #[test]
    fn reject_code_evaluation_failure_classification_covers_all_values() {
        let cases = [
            (RejectCode::MissingRequiredField, true),
            (RejectCode::InvalidFieldFormat, false),
            (RejectCode::InvalidFieldValue, false),
            (RejectCode::UnsupportedOrderType, false),
            (RejectCode::UnsupportedTimeInForce, false),
            (RejectCode::UnsupportedOrderAttribute, false),
            (RejectCode::DuplicateClientOrderId, false),
            (RejectCode::TooLateToEnter, false),
            (RejectCode::ExchangeClosed, false),
            (RejectCode::UnknownInstrument, true),
            (RejectCode::UnknownAccount, true),
            (RejectCode::UnknownVenue, true),
            (RejectCode::UnknownClearingAccount, true),
            (RejectCode::UnknownCollateralAsset, true),
            (RejectCode::InsufficientFunds, false),
            (RejectCode::InsufficientMargin, false),
            (RejectCode::InsufficientPosition, false),
            (RejectCode::CreditLimitExceeded, false),
            (RejectCode::RiskLimitExceeded, false),
            (RejectCode::OrderExceedsLimit, false),
            (RejectCode::OrderQtyExceedsLimit, false),
            (RejectCode::OrderNotionalExceedsLimit, false),
            (RejectCode::PositionLimitExceeded, false),
            (RejectCode::ConcentrationLimitExceeded, false),
            (RejectCode::LeverageLimitExceeded, false),
            (RejectCode::RateLimitExceeded, false),
            (RejectCode::PnlKillSwitchTriggered, false),
            (RejectCode::AccountBlocked, false),
            (RejectCode::AccountNotAuthorized, false),
            (RejectCode::ComplianceRestriction, false),
            (RejectCode::InstrumentRestricted, false),
            (RejectCode::JurisdictionRestriction, false),
            (RejectCode::WashTradePrevention, false),
            (RejectCode::SelfMatchPrevention, false),
            (RejectCode::ShortSaleRestriction, false),
            (RejectCode::RiskConfigurationMissing, true),
            (RejectCode::ReferenceDataUnavailable, true),
            (RejectCode::OrderValueCalculationFailed, true),
            (RejectCode::SystemUnavailable, true),
            (RejectCode::MarkPriceUnavailable, true),
            (RejectCode::AccountAdjustmentBoundsExceeded, false),
            (RejectCode::ArithmeticOverflow, true),
            (RejectCode::Custom, false),
            (RejectCode::Other, false),
        ];

        for (code, expected) in cases {
            assert_eq!(code.is_evaluation_failure(), expected, "{code}");
        }
    }

    #[test]
    fn reject_display_formats_policy_reason_and_details() {
        let reject = super::Reject::new(
            "TestPolicy",
            super::RejectScope::Order,
            RejectCode::Other,
            "something went wrong",
            "extra info",
        );
        assert_eq!(
            reject.to_string(),
            "[TestPolicy] something went wrong: extra info"
        );
    }

    #[test]
    fn reject_new_sets_default_user_data() {
        let reject = super::Reject::new(
            "TestPolicy",
            super::RejectScope::Order,
            RejectCode::Other,
            "reason",
            "details",
        );
        assert_eq!(reject.user_data, 0);
    }

    #[test]
    fn reject_with_user_data_overrides_default_payload() {
        let reject = super::Reject::new(
            "TestPolicy",
            super::RejectScope::Order,
            RejectCode::Other,
            "reason",
            "details",
        )
        .with_user_data(42usize);
        assert_eq!(reject.user_data, 42usize);
    }

    #[test]
    fn rejects_deref_gives_slice_access() {
        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "r",
            "d",
        )]);
        assert_eq!(rejects.len(), 1);
        assert_eq!(rejects[0].policy, "P");
    }

    #[test]
    fn rejects_display_single() {
        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "reason",
            "details",
        )]);
        assert_eq!(rejects.to_string(), "[P] reason: details");
    }

    #[test]
    fn rejects_display_multiple_joined_with_separator() {
        let rejects = super::Rejects::new(vec![
            super::Reject::new(
                "P1",
                super::RejectScope::Order,
                RejectCode::Other,
                "r1",
                "d1",
            ),
            super::Reject::new(
                "P2",
                super::RejectScope::Account,
                RejectCode::Other,
                "r2",
                "d2",
            ),
        ]);
        assert_eq!(rejects.to_string(), "[P1] r1: d1; [P2] r2: d2");
    }

    #[test]
    fn rejects_display_empty_produces_empty_string() {
        let rejects = super::Rejects::new(vec![]);
        assert_eq!(rejects.to_string(), "");
    }

    #[test]
    fn rejects_display_propagates_error_from_reject_fmt() {
        use std::fmt;
        use std::fmt::Write;

        struct ImmediateFailWriter;
        impl Write for ImmediateFailWriter {
            fn write_str(&mut self, _: &str) -> fmt::Result {
                Err(fmt::Error)
            }
        }

        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "r",
            "d",
        )]);
        assert!(fmt::write(&mut ImmediateFailWriter, format_args!("{rejects}")).is_err());
    }

    #[test]
    fn rejects_display_propagates_write_error() {
        use std::fmt;
        use std::fmt::Write;

        struct FailOnSeparator;
        impl Write for FailOnSeparator {
            fn write_str(&mut self, s: &str) -> fmt::Result {
                if s == "; " {
                    Err(fmt::Error)
                } else {
                    Ok(())
                }
            }
        }

        let rejects = super::Rejects::new(vec![
            super::Reject::new("P", super::RejectScope::Order, RejectCode::Other, "r", "d"),
            super::Reject::new("P", super::RejectScope::Order, RejectCode::Other, "r", "d"),
        ]);
        assert!(fmt::write(&mut FailOnSeparator, format_args!("{rejects}")).is_err());
    }
}