surfpool-types 1.5.0

Where you train before surfing Solana
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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
use std::{collections::HashMap, str::FromStr};

use serde::{Deserialize, Serialize};
use solana_clock::Slot;
use solana_pubkey::Pubkey;
use uuid::Uuid;

use crate::Idl;

// ========================================
// Constants Types (for UI comboboxes and LLM choices)
// ========================================

/// A single option within a constant definition
/// Used to define selectable values like AMM configs or well-known tokens
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConstantOption {
    /// Unique identifier for this option (e.g., "standard", "sol", "usdc")
    pub id: String,
    /// Human-readable label shown in UI (e.g., "Standard (25 bps)", "SOL (Wrapped)")
    pub label: String,
    /// Description explaining when to use this option
    #[serde(default)]
    pub description: Option<String>,
    /// The actual value (typically a pubkey string)
    pub value: String,
    /// Additional metadata for context (e.g., decimals, tick_spacing, fee rates)
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

/// A constant definition containing multiple selectable options
/// Used to define things like AMM fee tiers, well-known tokens, etc.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConstantDefinition {
    /// Human-readable label for this constant type (e.g., "Fee Tier", "Token")
    pub label: String,
    /// Description of what this constant represents
    #[serde(default)]
    pub description: Option<String>,
    /// The available options to choose from
    pub options: Vec<ConstantOption>,
}

impl ConstantDefinition {
    /// Get an option by its ID
    pub fn get_option(&self, id: &str) -> Option<&ConstantOption> {
        self.options.iter().find(|o| o.id == id)
    }

    /// Get the value for an option by ID
    pub fn get_value(&self, id: &str) -> Option<&str> {
        self.get_option(id).map(|o| o.value.as_str())
    }
}

// ========================================
// Core Scenarios Types
// ========================================

/// Defines how an account address should be determined
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
#[doc = "Defines how an account address should be determined"]
pub enum AccountAddress {
    /// A specific public key
    #[doc = "A specific public key"]
    Pubkey(String),
    /// A Program Derived Address with seeds
    #[doc = "A Program Derived Address with seeds"]
    #[serde(rename_all = "camelCase")]
    Pda {
        program_id: String,
        seeds: Vec<PdaSeed>,
    },
}

/// Seeds used for PDA derivation
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
#[doc = "Seeds used for PDA derivation"]
pub enum PdaSeed {
    Pubkey(String),
    String(String),
    Bytes(Vec<u8>),
    /// Reference to a property value
    PropertyRef(String),
    /// A u16 value converted to big-endian bytes (useful for config indices)
    U16Be(u16),
    /// Reference to a property that should be converted to u16 big-endian bytes
    U16BeRef(String),
    /// A u16 value converted to little-endian bytes (useful for Pyth shard IDs)
    U16Le(u16),
    /// Reference to a property that's a 32-byte hex string (e.g., Pyth feed ID)
    Bytes32Ref(String),
    /// A nested PDA derivation - derives a PDA from inner seeds and uses it as the seed
    #[serde(rename_all = "camelCase")]
    DerivedPda {
        program_id: String,
        seeds: Vec<PdaSeed>,
    },
}

impl PdaSeed {
    /// Convert a seed to bytes, optionally using values for PropertyRef resolution
    pub fn to_bytes(&self, values: Option<&HashMap<String, serde_json::Value>>) -> Option<Vec<u8>> {
        match self {
            PdaSeed::Pubkey(pk_str) => Pubkey::from_str(pk_str)
                .ok()
                .map(|pk| pk.to_bytes().to_vec()),
            PdaSeed::String(s) => Some(s.as_bytes().to_vec()),
            PdaSeed::Bytes(b) => Some(b.clone()),
            PdaSeed::PropertyRef(prop) => {
                values?.get(prop).and_then(|v| {
                    // Handle string values (could be pubkey or raw string)
                    if let Some(s) = v.as_str() {
                        if let Ok(pk) = Pubkey::from_str(s) {
                            return Some(pk.to_bytes().to_vec());
                        }
                        return Some(s.as_bytes().to_vec());
                    }
                    // Handle numeric values (u64)
                    if let Some(n) = v.as_u64() {
                        return Some(n.to_le_bytes().to_vec());
                    }
                    None
                })
            }
            PdaSeed::U16Be(n) => Some(n.to_be_bytes().to_vec()),
            PdaSeed::U16BeRef(prop) => {
                values?.get(prop).and_then(|v| {
                    // Handle numeric values - convert to u16 big-endian
                    if let Some(n) = v.as_u64() {
                        let n16 = u16::try_from(n).ok()?;
                        return Some(n16.to_be_bytes().to_vec());
                    }
                    None
                })
            }
            PdaSeed::U16Le(n) => Some(n.to_le_bytes().to_vec()),
            PdaSeed::Bytes32Ref(prop) => {
                values?.get(prop).and_then(|v| {
                    // Handle hex string values (e.g., "0xef0d8b6f..." for Pyth feed IDs)
                    if let Some(s) = v.as_str() {
                        // Remove 0x prefix if present
                        let hex_str = s.strip_prefix("0x").unwrap_or(s);
                        // Parse as 32-byte hex
                        if let Ok(bytes) = hex::decode(hex_str) {
                            if bytes.len() == 32 {
                                return Some(bytes);
                            }
                        }
                    }
                    None
                })
            }
            PdaSeed::DerivedPda { program_id, seeds } => {
                // Derive a nested PDA and use its pubkey as the seed
                let program_pubkey = Pubkey::from_str(program_id).ok()?;

                // Convert inner seeds to bytes
                let seed_bytes: Vec<Vec<u8>> = seeds
                    .iter()
                    .filter_map(|seed| seed.to_bytes(values))
                    .collect();

                // Ensure all seeds were converted successfully
                if seed_bytes.len() != seeds.len() {
                    return None;
                }

                // Create seed slices for find_program_address
                let seed_slices: Vec<&[u8]> = seed_bytes.iter().map(|s| s.as_slice()).collect();

                // Derive the nested PDA
                let (pda, _bump) = Pubkey::find_program_address(&seed_slices, &program_pubkey);
                Some(pda.to_bytes().to_vec())
            }
        }
    }
}

impl AccountAddress {
    /// Resolve the account address to a Pubkey
    /// For PDA addresses, this derives the address from the program_id and seeds
    /// For PropertyRef seeds, values map is used to resolve the reference
    pub fn resolve(&self, values: Option<&HashMap<String, serde_json::Value>>) -> Option<Pubkey> {
        match self {
            AccountAddress::Pubkey(pubkey_str) => Pubkey::from_str(pubkey_str).ok(),
            AccountAddress::Pda { program_id, seeds } => {
                let program_pubkey = Pubkey::from_str(program_id).ok()?;

                // Convert all seeds to bytes
                let seed_bytes: Vec<Vec<u8>> = seeds
                    .iter()
                    .filter_map(|seed| seed.to_bytes(values))
                    .collect();

                // Ensure all seeds were converted successfully
                if seed_bytes.len() != seeds.len() {
                    return None;
                }

                // Create seed slices for find_program_address
                let seed_slices: Vec<&[u8]> = seed_bytes.iter().map(|s| s.as_slice()).collect();

                // Derive the PDA
                let (pda, _bump) = Pubkey::find_program_address(&seed_slices, &program_pubkey);
                Some(pda)
            }
        }
    }

    /// Resolve the account address to a Pubkey without any values for PropertyRef
    /// This is a convenience method when no PropertyRef seeds are expected
    pub fn resolve_simple(&self) -> Option<Pubkey> {
        self.resolve(None)
    }

    /// Get the names of values that are referenced by PDA seeds
    /// These should be filtered out when applying account data overrides
    /// since they're only used for address derivation, not account data modification
    pub fn get_pda_seed_references(&self) -> Vec<String> {
        match self {
            AccountAddress::Pubkey(_) => vec![],
            AccountAddress::Pda { seeds, .. } => {
                let mut refs = Vec::new();
                Self::collect_seed_references(seeds, &mut refs);
                refs
            }
        }
    }

    /// Recursively collect property references from seeds
    fn collect_seed_references(seeds: &[PdaSeed], refs: &mut Vec<String>) {
        for seed in seeds {
            match seed {
                PdaSeed::PropertyRef(name) => refs.push(name.clone()),
                PdaSeed::U16BeRef(name) => refs.push(name.clone()),
                PdaSeed::Bytes32Ref(name) => refs.push(name.clone()),
                PdaSeed::DerivedPda { seeds: inner, .. } => {
                    Self::collect_seed_references(inner, refs);
                }
                _ => {}
            }
        }
    }
}

/// The type of a property - determines how it's rendered in the UI
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PropertyKind {
    /// A regular field from the IDL (default behavior)
    #[default]
    Field,
    /// A reference to a constant definition (renders as dropdown/combobox in UI)
    ConstantRef,
}

/// Defines a property in a template with full metadata
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Property {
    /// The path to the field in the IDL (e.g., "liquidity", "fees.swap_fee_numerator")
    pub path: String,
    /// The type of property - determines rendering behavior
    #[serde(default, rename = "type")]
    pub kind: PropertyKind,
    /// Human-readable label for the UI (optional, defaults to path)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Description of the field (optional, can come from IDL)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// For constant_ref type: the name of the constant definition to use
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub constant: Option<String>,
}

impl Property {
    /// Create a new field property
    pub fn field(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            kind: PropertyKind::Field,
            label: None,
            description: None,
            constant: None,
        }
    }

    /// Create a new constant_ref property
    pub fn constant_ref(path: impl Into<String>, constant: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            kind: PropertyKind::ConstantRef,
            label: None,
            description: None,
            constant: Some(constant.into()),
        }
    }

    /// Check if this is a constant reference
    pub fn is_constant_ref(&self) -> bool {
        matches!(self.kind, PropertyKind::ConstantRef)
    }

    /// Get the constant name if this is a constant reference
    pub fn constant_name(&self) -> Option<&str> {
        self.constant.as_deref()
    }

    /// Get the display label (falls back to path if no label set)
    pub fn display_label(&self) -> &str {
        self.label.as_deref().unwrap_or(&self.path)
    }
}

/// Legacy tagged property representation.
///
/// Use [`Property`] for new code. This type remains deserializable for callers
/// that still send the old tagged JSON shape, such as
/// `{"type":"field","name":"price"}`.
#[deprecated(
    since = "1.5.0",
    note = "use Property; PropertyType remains only for legacy tagged JSON compatibility"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum PropertyType {
    /// A regular field from the IDL (default behavior)
    Field { name: String },
    /// A reference to a constant definition (renders as combobox in UI)
    ConstantRef { name: String, constant: String },
}

#[allow(deprecated)]
impl PropertyType {
    /// Get the property name regardless of type
    pub fn name(&self) -> &str {
        match self {
            PropertyType::Field { name } => name,
            PropertyType::ConstantRef { name, .. } => name,
        }
    }

    /// Check if this is a constant reference
    pub fn is_constant_ref(&self) -> bool {
        matches!(self, PropertyType::ConstantRef { .. })
    }

    /// Get the constant name if this is a constant reference
    pub fn constant_name(&self) -> Option<&str> {
        match self {
            PropertyType::ConstantRef { constant, .. } => Some(constant),
            _ => None,
        }
    }
}

#[allow(deprecated)]
impl From<PropertyType> for Property {
    fn from(pt: PropertyType) -> Self {
        match pt {
            PropertyType::Field { name } => Property::field(name),
            PropertyType::ConstantRef { name, constant } => Property::constant_ref(name, constant),
        }
    }
}

/// A reusable template for creating account overrides
/// Values are mapped directly to IDL fields using dot notation (e.g., "agg.price", "expo")
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OverrideTemplate {
    /// Unique identifier for the template
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Description of what this template does
    pub description: String,
    /// Protocol this template is for (e.g., "Pyth", "Switchboard")
    pub protocol: String,
    /// IDL for the account structure - defines all available fields and types
    pub idl: Idl,
    /// How to determine the account address
    pub address: AccountAddress,
    /// Account type name from the IDL (e.g., "PriceAccount")
    /// This specifies which account struct in the IDL to use
    pub account_type: String,
    /// List of editable properties with full metadata
    pub properties: Vec<Property>,
    /// Protocol-specific constants (e.g., AMM configs, well-known tokens)
    #[serde(default)]
    pub constants: HashMap<String, ConstantDefinition>,
    /// Tags for categorization and search
    pub tags: Vec<String>,
    /// Optional context/instructions specifically for LLMs using this template
    /// This helps LLMs understand how to correctly use the template
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub llm_context: Option<String>,
}

impl OverrideTemplate {
    pub fn new(
        id: String,
        name: String,
        description: String,
        protocol: String,
        idl: Idl,
        address: AccountAddress,
        properties: Vec<Property>,
        account_type: String,
    ) -> Self {
        Self {
            id,
            name,
            description,
            protocol,
            idl,
            address,
            account_type,
            properties,
            constants: HashMap::new(),
            tags: Vec::new(),
            llm_context: None,
        }
    }

    /// Get a constant definition by name
    pub fn get_constant(&self, name: &str) -> Option<&ConstantDefinition> {
        self.constants.get(name)
    }

    /// Check if a property is a constant reference
    pub fn is_property_constant_ref(&self, property_name: &str) -> bool {
        self.properties
            .iter()
            .any(|p| p.path == property_name && p.is_constant_ref())
    }

    /// Get the constant definition for a property if it's a constant reference
    pub fn get_property_constant(&self, property_name: &str) -> Option<&ConstantDefinition> {
        self.properties
            .iter()
            .find(|p| p.path == property_name)
            .and_then(|p| p.constant_name())
            .and_then(|const_name| self.constants.get(const_name))
    }

    /// Get a property by its path
    pub fn get_property(&self, path: &str) -> Option<&Property> {
        self.properties.iter().find(|p| p.path == path)
    }

    /// Get the list of property paths (for backward compatibility)
    pub fn property_paths(&self) -> Vec<&str> {
        self.properties.iter().map(|p| p.path.as_str()).collect()
    }
}

/// A concrete instance of an override template with specific values
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct OverrideInstance {
    /// Unique identifier for this instance (UUID v4)
    #[schemars(description = "Unique identifier for this instance (UUID v4 format)")]
    pub id: String,
    /// Reference to the template being used - MUST match a template id from get_override_templates
    #[schemars(
        description = "Template ID from get_override_templates (e.g., 'raydium-clmm-custom', 'kamino-obligation-health')"
    )]
    pub template_id: String,
    /// Values for the template properties as a JSON object (NOT a string)
    #[schemars(
        description = "JSON object mapping property names to values. Keys must be from template.properties. Example: {\"liquidity\": 1000000, \"sqrt_price_x64\": 18446744073709551616}"
    )]
    pub values: HashMap<String, serde_json::Value>,
    /// Relative slot when this override should be applied (1 = 400ms after registration)
    #[schemars(
        description = "Slot offset from scenario registration (integer, e.g., 1, 2, 3). Each slot is ~400ms."
    )]
    pub scenario_relative_slot: Slot,
    /// Optional human-readable label for this instance
    #[schemars(description = "Human-readable label describing what this override does")]
    pub label: Option<String>,
    /// Whether this override is enabled
    #[schemars(description = "Whether this override is active (true/false)")]
    pub enabled: bool,
    /// Whether to fetch fresh account data just before transaction execution
    #[schemars(
        description = "If true, fetches fresh account data from mainnet before applying override"
    )]
    #[serde(default)]
    pub fetch_before_use: bool,
    /// Account address to override - use pubkey for known addresses or pda for derived addresses
    #[schemars(
        description = "Account address: either {\"pubkey\": \"base58_address\"} or {\"pda\": {\"programId\": \"...\", \"seeds\": [...]}}"
    )]
    pub account: AccountAddress,
}

impl OverrideInstance {
    pub fn new(template_id: String, scenario_relative_slot: Slot, account: AccountAddress) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            template_id,
            values: HashMap::new(),
            scenario_relative_slot,
            label: None,
            enabled: true,
            fetch_before_use: false,
            account,
        }
    }

    pub fn with_values(mut self, values: HashMap<String, serde_json::Value>) -> Self {
        self.values = values;
        self
    }

    pub fn with_label(mut self, label: String) -> Self {
        self.label = Some(label);
        self
    }
}

/// A scenario containing a timeline of overrides
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct Scenario {
    /// Unique identifier for the scenario (UUID v4 format)
    #[schemars(
        description = "Unique identifier for the scenario (UUID v4 format, e.g., '550e8400-e29b-41d4-a716-446655440000')"
    )]
    pub id: String,
    /// Human-readable name
    #[schemars(description = "Human-readable name for the scenario")]
    pub name: String,
    /// Description of this scenario
    #[schemars(description = "Description of what this scenario does")]
    pub description: String,
    /// List of override instances in this scenario - MUST be an array, NOT a string
    #[schemars(
        description = "Array of override instances. IMPORTANT: This must be a JSON array [], not a JSON string. Each element is an OverrideInstance object."
    )]
    pub overrides: Vec<OverrideInstance>,
    /// Tags for categorization
    #[schemars(
        description = "Array of string tags for categorization (e.g., ['liquidation', 'arbitrage'])"
    )]
    pub tags: Vec<String>,
}

impl Scenario {
    pub fn new(name: String, description: String) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            name,
            description,
            overrides: Vec::new(),
            tags: Vec::new(),
        }
    }

    pub fn add_override(&mut self, override_instance: OverrideInstance) {
        self.overrides.push(override_instance);
        // Sort by slot for efficient lookup
        self.overrides.sort_by_key(|o| o.scenario_relative_slot);
    }

    pub fn remove_override(&mut self, override_id: &str) {
        self.overrides.retain(|o| o.id != override_id);
    }

    pub fn get_overrides_for_slot(&self, slot: Slot) -> Vec<&OverrideInstance> {
        self.overrides
            .iter()
            .filter(|o| o.enabled && o.scenario_relative_slot == slot)
            .collect()
    }
}

/// Configuration for scenario execution
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScenarioConfig {
    /// Whether scenarios are enabled
    pub enabled: bool,
    /// Currently active scenario
    pub active_scenario: Option<String>,
    /// Whether to auto-save scenario changes
    pub auto_save: bool,
}

impl Default for ScenarioConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            active_scenario: None,
            auto_save: true,
        }
    }
}

// ========================================
// YAML Template File Types
// ========================================

/// YAML representation of an override template loaded from file
/// References an external IDL file via idl_file_path
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlOverrideTemplateFile {
    pub id: String,
    pub name: String,
    pub description: String,
    pub protocol: String,
    pub version: String,
    pub account_type: String,
    #[serde(default)]
    pub properties: Vec<YamlProperty>,
    #[serde(default)]
    pub constants: HashMap<String, YamlConstantDefinition>,
    pub idl_file_path: String,
    pub address: YamlAccountAddress,
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional context/instructions specifically for LLMs using this template
    #[serde(default)]
    pub llm_context: Option<String>,
}

impl YamlOverrideTemplateFile {
    /// Convert file-based template to runtime OverrideTemplate with loaded IDL
    pub fn to_override_template(self, idl: Idl) -> OverrideTemplate {
        OverrideTemplate {
            id: self.id,
            name: self.name,
            description: self.description,
            protocol: self.protocol,
            idl,
            address: self.address.into(),
            account_type: self.account_type,
            properties: self.properties.into_iter().map(Into::into).collect(),
            constants: self
                .constants
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            tags: self.tags,
            llm_context: self.llm_context,
        }
    }
}

/// YAML representation of a constant option
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlConstantOption {
    /// Unique identifier for this option
    pub id: String,
    /// Human-readable label
    pub label: String,
    /// Description of when to use this option
    #[serde(default)]
    pub description: Option<String>,
    /// The actual value (typically a pubkey)
    pub value: String,
    /// Additional metadata
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
}

impl From<YamlConstantOption> for ConstantOption {
    fn from(yaml: YamlConstantOption) -> Self {
        ConstantOption {
            id: yaml.id,
            label: yaml.label,
            description: yaml.description,
            value: yaml.value,
            metadata: yaml.metadata,
        }
    }
}

/// Source for constant options - either inline or from verified tokens registry
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum YamlConstantSource {
    /// Inline options defined in the YAML
    Inline { options: Vec<YamlConstantOption> },
    /// Reference to the verified tokens registry
    TokensRef {
        /// Type of reference - currently only "verified_tokens" is supported
        source: String,
        /// Optional filter for which tokens to include (e.g., by tags like "major", "stable")
        #[serde(default)]
        filter_tags: Vec<String>,
        /// Optional limit on number of tokens to include
        #[serde(default)]
        limit: Option<usize>,
    },
}

/// YAML representation of a constant definition
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlConstantDefinition {
    /// Human-readable label for this constant type
    pub label: String,
    /// Description of what this constant represents
    #[serde(default)]
    pub description: Option<String>,
    /// The source of options - either inline or from a reference
    #[serde(flatten)]
    pub source: YamlConstantSource,
}

impl YamlConstantDefinition {
    /// Convert to runtime ConstantDefinition, resolving verified tokens references
    pub fn to_constant_definition(self) -> ConstantDefinition {
        let options = match self.source {
            YamlConstantSource::Inline { options } => options.into_iter().map(Into::into).collect(),
            YamlConstantSource::TokensRef {
                source,
                filter_tags,
                limit,
            } => {
                if source == "verified_tokens" {
                    use crate::verified_tokens::VERIFIED_TOKENS_BY_SYMBOL;

                    let mut tokens: Vec<_> = VERIFIED_TOKENS_BY_SYMBOL
                        .iter()
                        .filter(|(_, _token)| {
                            // If no filter tags specified, include all tokens
                            if filter_tags.is_empty() {
                                return true;
                            }
                            // Check if token has any of the filter tags
                            // The tags are stored in the CSV but not parsed into TokenInfo yet
                            // For now, we'll include all tokens when filter is specified
                            // TODO: Parse tags from CSV into TokenInfo struct
                            true
                        })
                        .map(|(symbol, token)| ConstantOption {
                            id: symbol.to_lowercase(),
                            label: format!("{} ({})", token.symbol, token.name),
                            description: Some(token.name.clone()),
                            value: token.address.clone(),
                            metadata: {
                                let mut meta = HashMap::new();
                                meta.insert(
                                    "symbol".to_string(),
                                    serde_json::Value::String(token.symbol.clone()),
                                );
                                meta.insert(
                                    "decimals".to_string(),
                                    serde_json::Value::Number(token.decimals.into()),
                                );
                                if let Some(ref logo) = token.logo_uri {
                                    meta.insert(
                                        "logo_uri".to_string(),
                                        serde_json::Value::String(logo.clone()),
                                    );
                                }
                                meta
                            },
                        })
                        .collect();

                    // Sort by symbol for consistent ordering
                    tokens.sort_by(|a, b| a.id.cmp(&b.id));

                    // Apply limit if specified
                    if let Some(limit) = limit {
                        tokens.truncate(limit);
                    }

                    tokens
                } else {
                    // Unknown source type - return empty options
                    Vec::new()
                }
            }
        };

        ConstantDefinition {
            label: self.label,
            description: self.description,
            options,
        }
    }
}

// Keep From impl for backward compatibility but use the new method
impl From<YamlConstantDefinition> for ConstantDefinition {
    fn from(yaml: YamlConstantDefinition) -> Self {
        yaml.to_constant_definition()
    }
}

/// YAML representation of a property (supports both simple string and full object format)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum YamlProperty {
    /// Simple string format: just the path (e.g., "liquidity", "fees.swap_fee_numerator")
    Simple(String),
    /// Full object format with all metadata
    Full {
        /// The path to the field in the IDL
        path: String,
        /// The type of property: "field" (default) or "constant_ref"
        #[serde(default, rename = "type")]
        kind: Option<String>,
        /// Human-readable label for the UI (optional)
        #[serde(default)]
        label: Option<String>,
        /// Description of the field (optional)
        #[serde(default)]
        description: Option<String>,
        /// For constant_ref type: the name of the constant definition to use
        #[serde(default)]
        constant: Option<String>,
    },
}

impl From<YamlProperty> for Property {
    fn from(yaml: YamlProperty) -> Self {
        match yaml {
            YamlProperty::Simple(path) => Property::field(path),
            YamlProperty::Full {
                path,
                kind,
                label,
                description,
                constant,
            } => {
                let kind = match kind.as_deref() {
                    Some("constant_ref") => PropertyKind::ConstantRef,
                    _ => PropertyKind::Field,
                };
                Property {
                    path,
                    kind,
                    label,
                    description,
                    constant,
                }
            }
        }
    }
}

/// YAML representation of a typed property (deprecated, for backward compatibility)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum YamlPropertyType {
    /// A regular field from the IDL
    Field { name: String },
    /// A reference to a constant definition
    ConstantRef { name: String, constant: String },
}

impl From<YamlPropertyType> for Property {
    fn from(yaml: YamlPropertyType) -> Self {
        match yaml {
            YamlPropertyType::Field { name } => Property::field(name),
            YamlPropertyType::ConstantRef { name, constant } => {
                Property::constant_ref(name, constant)
            }
        }
    }
}

#[allow(deprecated)]
impl From<YamlPropertyType> for PropertyType {
    fn from(yaml: YamlPropertyType) -> Self {
        match yaml {
            YamlPropertyType::Field { name } => PropertyType::Field { name },
            YamlPropertyType::ConstantRef { name, constant } => {
                PropertyType::ConstantRef { name, constant }
            }
        }
    }
}

/// Collection of override templates sharing the same IDL
/// Used when one YAML file defines multiple templates (e.g., multiple Pyth price feeds)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlOverrideTemplateCollection {
    /// Protocol these templates are for
    pub protocol: String,
    /// Version identifier
    pub version: String,
    /// Account type name from the IDL (optional, can be overridden per template)
    #[serde(default)]
    pub account_type: Option<String>,
    /// Path to shared IDL file
    pub idl_file_path: String,
    /// Common tags for all templates
    #[serde(default)]
    pub tags: Vec<String>,
    /// Protocol-specific constants shared by all templates in this collection
    #[serde(default)]
    pub constants: HashMap<String, YamlConstantDefinition>,
    /// The templates
    pub templates: Vec<YamlOverrideTemplateEntry>,
}

/// Individual template entry in a collection
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlOverrideTemplateEntry {
    pub id: String,
    pub name: String,
    pub description: String,
    /// Account type name from the IDL (overrides collection-level account_type)
    #[serde(default)]
    pub idl_account_name: Option<String>,
    /// Properties with full metadata
    #[serde(default)]
    pub properties: Vec<YamlProperty>,
    pub address: YamlAccountAddress,
    /// Optional context/instructions specifically for LLMs using this template
    #[serde(default)]
    pub llm_context: Option<String>,
}

impl YamlOverrideTemplateCollection {
    /// Convert collection to runtime OverrideTemplates with loaded IDL
    pub fn to_override_templates(self, idl: Idl) -> Vec<OverrideTemplate> {
        // Convert constants once for sharing
        let constants: HashMap<String, ConstantDefinition> = self
            .constants
            .into_iter()
            .map(|(k, v)| (k, v.into()))
            .collect();

        let default_account_type = self.account_type.clone().unwrap_or_default();

        self.templates
            .into_iter()
            .map(|entry| OverrideTemplate {
                id: entry.id,
                name: entry.name,
                description: entry.description,
                protocol: self.protocol.clone(),
                idl: idl.clone(),
                address: entry.address.into(),
                account_type: entry
                    .idl_account_name
                    .unwrap_or_else(|| default_account_type.clone()),
                properties: entry.properties.into_iter().map(Into::into).collect(),
                constants: constants.clone(),
                tags: self.tags.clone(),
                llm_context: entry.llm_context,
            })
            .collect()
    }
}

/// YAML representation of an override template with embedded IDL
/// Used for RPC methods where file access is not available
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct YamlOverrideTemplate {
    pub id: String,
    pub name: String,
    pub description: String,
    pub protocol: String,
    pub version: String,
    pub account_type: String,
    pub idl: Idl,
    pub address: YamlAccountAddress,
    #[serde(default)]
    pub properties: Vec<YamlProperty>,
    #[serde(default)]
    pub constants: HashMap<String, YamlConstantDefinition>,
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional context/instructions specifically for LLMs using this template
    #[serde(default)]
    pub llm_context: Option<String>,
}

impl YamlOverrideTemplate {
    /// Convert to runtime OverrideTemplate
    pub fn to_override_template(self) -> OverrideTemplate {
        OverrideTemplate {
            id: self.id,
            name: self.name,
            description: self.description,
            protocol: self.protocol,
            idl: self.idl,
            address: self.address.into(),
            account_type: self.account_type,
            properties: self.properties.into_iter().map(Into::into).collect(),
            constants: self
                .constants
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            tags: self.tags,
            llm_context: self.llm_context,
        }
    }
}

/// YAML representation of account address
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum YamlAccountAddress {
    Pubkey {
        #[serde(default)]
        value: Option<String>,
    },
    Pda {
        program_id: String,
        seeds: Vec<YamlPdaSeed>,
    },
}

impl From<YamlAccountAddress> for AccountAddress {
    fn from(yaml: YamlAccountAddress) -> Self {
        match yaml {
            YamlAccountAddress::Pubkey { value } => {
                AccountAddress::Pubkey(value.unwrap_or_default())
            }
            YamlAccountAddress::Pda { program_id, seeds } => AccountAddress::Pda {
                program_id,
                seeds: seeds.into_iter().map(|s| s.into()).collect(),
            },
        }
    }
}

/// YAML representation of PDA seeds
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum YamlPdaSeed {
    String {
        value: String,
    },
    Bytes {
        value: Vec<u8>,
    },
    Pubkey {
        value: String,
    },
    PropertyRef {
        value: String,
    },
    /// A u16 value converted to big-endian bytes
    U16Be {
        value: u16,
    },
    /// Reference to a property that should be converted to u16 big-endian bytes
    U16BeRef {
        value: String,
    },
    /// A u16 value converted to little-endian bytes (useful for Pyth shard IDs)
    U16Le {
        value: u16,
    },
    /// Reference to a property that's a 32-byte hex string (e.g., Pyth feed ID)
    Bytes32Ref {
        value: String,
    },
    /// A nested PDA derivation - derives a PDA from inner seeds and uses it as the seed
    DerivedPda {
        program_id: String,
        seeds: Vec<YamlPdaSeed>,
    },
}

impl From<YamlPdaSeed> for PdaSeed {
    fn from(yaml: YamlPdaSeed) -> Self {
        match yaml {
            YamlPdaSeed::String { value } => PdaSeed::String(value),
            YamlPdaSeed::Bytes { value } => PdaSeed::Bytes(value),
            YamlPdaSeed::Pubkey { value } => PdaSeed::Pubkey(value),
            YamlPdaSeed::PropertyRef { value } => PdaSeed::PropertyRef(value),
            YamlPdaSeed::U16Be { value } => PdaSeed::U16Be(value),
            YamlPdaSeed::U16BeRef { value } => PdaSeed::U16BeRef(value),
            YamlPdaSeed::U16Le { value } => PdaSeed::U16Le(value),
            YamlPdaSeed::Bytes32Ref { value } => PdaSeed::Bytes32Ref(value),
            YamlPdaSeed::DerivedPda { program_id, seeds } => PdaSeed::DerivedPda {
                program_id,
                seeds: seeds.into_iter().map(|s| s.into()).collect(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use serde_json::json;

    use super::PdaSeed;

    #[test]
    fn u16_be_ref_rejects_out_of_range_values() {
        let seed = PdaSeed::U16BeRef("index".to_string());
        let values = HashMap::from([("index".to_string(), json!(70_000))]);

        assert_eq!(seed.to_bytes(Some(&values)), None);
    }

    #[test]
    fn u16_be_ref_encodes_in_range_values() {
        let seed = PdaSeed::U16BeRef("index".to_string());
        let values = HashMap::from([("index".to_string(), json!(513))]);

        assert_eq!(seed.to_bytes(Some(&values)), Some(vec![2, 1]));
    }
}