degenbot-cli-core 0.6.0-alpha.14

Command semantics + the database command arms for the degenbot console (ADR-051 D1) - pyo3-free and clap-free.
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
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
//! Typed command reports (ADR-051 D1: execution returns typed results; the
//! facade renders them — Q1).

use std::path::PathBuf;

use alloy::primitives::U256;
use degenbot_db::ops::HealReport;
use degenbot_db::SchemaState;

use crate::error::{CliError, ExitCode};
use crate::pool::PoolFamily;
use crate::strategy::StrategyFacetDescriptor;

/// The typed result of one command execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommandReport {
    /// A `database` command report.
    Database(DatabaseReport),
    /// An `exchange` command report.
    Exchange(ExchangeReport),
    /// A `pool` command report.
    Pool(PoolReport),
    /// An `aave` command report.
    Aave(AaveReport),
    /// A `fleet` command report.
    Fleet(FleetReport),
    /// A `path` command report.
    Path(PathReport),
    /// A `strategy` command report (ADR-055 facets).
    Strategy(StrategyReport),
    /// A `config` command report.
    Config(ConfigReport),
}

impl CommandReport {
    /// The operator-facing lines the argv facade renders.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Database(report) => report.render_lines(),
            Self::Exchange(report) => report.render_lines(),
            Self::Pool(report) => report.render_lines(),
            Self::Aave(report) => report.render_lines(),
            Self::Fleet(report) => report.render_lines(),
            Self::Path(report) => report.render_lines(),
            Self::Strategy(report) => report.render_lines(),
            Self::Config(report) => report.render_lines(),
        }
    }
}

/// One resolved (or absent) driver-domain value, as `config show` renders it.
///
/// The key is the operator's own spelling: a declared key
/// (`session.chain_id`, `database.path`), a per-chain endpoint entry
/// (`nodes.ws[8453]`), or a whole transport's explicit slot (`nodes.ws`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigValue {
    /// The key as the operator writes it.
    pub key: String,
    /// The value, verbatim; `(unresolved)` is carried by the absent source
    /// rather than a sentinel string.
    pub value: String,
    /// The layer that supplied the value, or `None` when no layer did.
    pub source: Option<degenbot_config::Source>,
}

impl ConfigValue {
    /// A value with its winning layer.
    #[must_use]
    pub fn new(key: &str, value: String, source: degenbot_config::Source) -> Self {
        Self {
            key: key.to_string(),
            value,
            source: Some(source),
        }
    }

    /// A key no layer supplied: reported, never guessed and never omitted.
    #[must_use]
    pub fn unresolved(key: &str) -> Self {
        Self {
            key: key.to_string(),
            value: String::new(),
            source: None,
        }
    }

    /// The `key = value` line (the file view). The value is redacted at
    /// render time: the file keeps the operator's bytes, but a rendered line
    /// never prints a credential (ADR-062 D12).
    #[must_use]
    pub fn line(&self) -> String {
        match self.source {
            Some(_) => format!(
                "{} = {}",
                self.key,
                degenbot_config::redact_uri(&self.value)
            ),
            None => format!("{} = (unresolved)", self.key),
        }
    }

    /// The `key = value (source)` line (`config show --resolved`), redacted.
    #[must_use]
    pub fn resolved_line(&self) -> String {
        match self.source {
            Some(source) => format!(
                "{} = {} ({source})",
                self.key,
                degenbot_config::redact_uri(&self.value)
            ),
            None => format!("{} = (unresolved)", self.key),
        }
    }
}

/// The typed result of a `config` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigReport {
    /// `config show`: the driver-domain values, annotated with their winning
    /// layer when `resolved` was asked for.
    Shown {
        /// The config file in play, absent when no location resolves.
        file: Option<PathBuf>,
        /// The values, in the operator's key order.
        values: Vec<ConfigValue>,
        /// Whether each line carries its winning layer (`--resolved`).
        resolved: bool,
    },
    /// `config path`: the config file the mutating arms read and write.
    Path(PathBuf),
    /// `config get <key>`: one resolved value and its winning layer (or the
    /// absent layer for an unresolved key).
    Got {
        /// The key as the operator spelled it.
        key: String,
        /// The resolved value, verbatim (redacted at render time).
        value: String,
        /// The layer that supplied it, or `None` when none did.
        source: Option<degenbot_config::Source>,
    },
    /// `config set <key> <value>`: the override was written.
    Set {
        /// The key as the operator spelled it.
        key: String,
        /// The value written, verbatim (redacted at render time).
        value: String,
        /// Whether the write applies or an env var shadows it.
        outcome: crate::strategy::MutationOutcome,
    },
    /// `config unset <key>`: the override was dropped.
    Unset {
        /// The key as the operator spelled it.
        key: String,
        /// Whether an env var still supplies the key at load time.
        outcome: crate::strategy::MutationOutcome,
    },
}

impl ConfigReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Shown {
                file,
                values,
                resolved,
            } => {
                // The file in play is also the mutating arms' write target, so
                // an absent file is named as such rather than presented as a
                // file the values were read from.
                let mut lines = vec![match file {
                    Some(path) if path.exists() => format!("config = {}", path.display()),
                    Some(path) => format!("config = {} (not yet created)", path.display()),
                    None => "config = (no config file location)".to_string(),
                }];
                lines.extend(values.iter().map(|value| {
                    if *resolved {
                        value.resolved_line()
                    } else {
                        value.line()
                    }
                }));
                lines
            }
            Self::Path(path) => vec![path.display().to_string()],
            Self::Got { key, value, source } => vec![match source {
                Some(source) => {
                    format!("{key} = {} ({source})", degenbot_config::redact_uri(value))
                }
                None => format!("{key} = (unresolved)"),
            }],
            Self::Set {
                key,
                value,
                outcome,
            } => vec![
                format!("set {key} = {}", degenbot_config::redact_uri(value)),
                shadow_line(outcome),
            ],
            Self::Unset { key, outcome } => {
                vec![format!("removed {key}"), shadow_line(outcome)]
            }
        }
    }
}

/// The typed result of the execution entry.
#[derive(Debug)]
pub struct CommandOutcome {
    result: Result<CommandReport, CliError>,
    /// The process exit code derived at the single `From<&CliError>` site.
    pub exit_code: ExitCode,
}

impl CommandOutcome {
    /// Bundle a result with its derived exit code.
    #[must_use]
    pub(crate) const fn new(result: Result<CommandReport, CliError>, exit_code: ExitCode) -> Self {
        Self { result, exit_code }
    }

    /// The typed report, when the command completed.
    #[must_use]
    pub fn report(&self) -> Option<&CommandReport> {
        self.result.as_ref().ok()
    }

    /// The typed failure, when the command did not complete.
    #[must_use]
    pub fn error(&self) -> Option<&CliError> {
        self.result.as_ref().err()
    }
}

/// Which dry-run arm produced a [`DatabaseReport::DryRun`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DryRunKind {
    /// `database cutover --dry-run`.
    Cutover,
    /// `database heal --dry-run`.
    Heal,
}

/// The outcome of a successful `database cutover` (pre-state derived).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CutoverOutcome {
    /// The DB was Alembic-stamped and is now Rust-owned.
    Converted,
    /// The DB was already Rust-owned; the cutover was a no-op.
    AlreadyRustOwned,
}

/// The typed result of a `database` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatabaseReport {
    /// `backup` completed.
    BackedUp {
        /// The source database path.
        source: PathBuf,
        /// The written backup path.
        backup: PathBuf,
    },
    /// `reset` recreated the database.
    Reset {
        /// The database path.
        path: PathBuf,
    },
    /// `compact` vacuumed the database.
    Compacted {
        /// The database path.
        path: PathBuf,
    },
    /// `inspect` read the schema state (writes nothing).
    Inspected {
        /// The database path.
        path: PathBuf,
        /// The observed schema state.
        state: SchemaState,
    },
    /// `cutover` flipped schema ownership.
    Cutover {
        /// The database path.
        path: PathBuf,
        /// The observed pre-cutover schema state.
        state: SchemaState,
        /// Whether the cutover converted or no-op'd.
        outcome: CutoverOutcome,
    },
    /// `heal` rebuilt the database out-of-place.
    Healed {
        /// The database path.
        path: PathBuf,
        /// The heal report (rows copied, `.bak` path, warnings).
        report: HealReport,
    },
    /// A `--dry-run` observed the schema state and wrote nothing.
    DryRun {
        /// The database path.
        path: PathBuf,
        /// The observed schema state.
        state: SchemaState,
        /// Which dry-run arm ran.
        kind: DryRunKind,
    },
}

impl DatabaseReport {
    /// The operator-facing lines for this report (the ported click `echo` text).
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::BackedUp { backup, .. } => {
                vec![format!("Backed up SQLite database to {}", backup.display())]
            }
            Self::Reset { path } => {
                vec![format!(
                    "Initialized new SQLite database at {}",
                    path.display()
                )]
            }
            Self::Compacted { path } => {
                vec![format!("Compacted SQLite database at {}", path.display())]
            }
            Self::Inspected { state, .. } => {
                vec![format!("Schema state: {}.", schema_state_label(state))]
            }
            Self::Cutover { path, outcome, .. } => match outcome {
                CutoverOutcome::Converted => vec![format!(
                    "Cut over database at {} from Alembic to Rust ownership (the \
                     `alembic_version` table was dropped and `_degenbot_db_schema_version` \
                     was stamped).",
                    path.display()
                )],
                CutoverOutcome::AlreadyRustOwned => {
                    vec!["The database is already Rust-owned; cutover was a no-op.".to_string()]
                }
            },
            Self::Healed { path, report } => healed_lines(path, report),
            Self::DryRun { state, kind, .. } => vec![match kind {
                DryRunKind::Cutover => cutover_dry_run_line(state),
                DryRunKind::Heal => heal_dry_run_line(state),
            }],
        }
    }
}

/// Whether an `exchange activate` flipped the row or found it already active.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivateOutcome {
    /// The row was newly activated (or re-activated from inactive).
    Activated,
    /// The row was already active; nothing was written.
    AlreadyActive,
}

/// Whither an `exchange deactivate`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeactivateOutcome {
    /// The row was newly deactivated.
    Deactivated,
    /// The row was already inactive.
    AlreadyDeactivated,
    /// The DB has no row for the pair.
    NoEntry,
}

/// Whether an `exchange list` row's DB entry exists, and its active state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExchangeActiveState {
    /// The DB row exists with `active = true`.
    Active,
    /// The DB row exists with `active = false`.
    Inactive,
    /// The DB has no row for the pair (never activated).
    NoEntry,
}

impl ExchangeActiveState {
    /// The operator-facing state word in the `exchange list` lines.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::Inactive => "inactive",
            Self::NoEntry => "not in database",
        }
    }
}

/// One `exchange list` row: a supported `(chain, DEX)` pair and its DB state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExchangeListRow {
    /// The chain id.
    pub chain_id: u64,
    /// The human chain label.
    pub chain_label: &'static str,
    /// The human DEX label.
    pub display_name: &'static str,
    /// The DEX name slug.
    pub dex_slug: &'static str,
    /// The exchange factory (V4: the `PoolManager`), checksummed.
    pub factory: String,
    /// The DB active state.
    pub state: ExchangeActiveState,
}

/// The typed result of an `exchange` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExchangeReport {
    /// `exchange activate`.
    Activated {
        /// The resolved chain id.
        chain_id: u64,
        /// The human chain label.
        chain_label: &'static str,
        /// The human DEX label.
        display_name: &'static str,
        /// The DEX name slug.
        dex_slug: &'static str,
        /// Whether the row flipped or was already active.
        outcome: ActivateOutcome,
    },
    /// `exchange deactivate`.
    Deactivated {
        /// The resolved chain id.
        chain_id: u64,
        /// The human chain label.
        chain_label: &'static str,
        /// The human DEX label.
        display_name: &'static str,
        /// The DEX name slug.
        dex_slug: &'static str,
        /// The deactivation outcome.
        outcome: DeactivateOutcome,
    },
    /// `exchange list`.
    Listed {
        /// One row per supported `(chain, DEX)` pair, in declaration order.
        rows: Vec<ExchangeListRow>,
    },
}

impl ExchangeReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Activated {
                chain_id,
                chain_label,
                display_name,
                outcome,
                ..
            } => match outcome {
                ActivateOutcome::Activated => vec![format!(
                    "Activated {display_name} on {chain_label} (chain ID {chain_id})."
                )],
                ActivateOutcome::AlreadyActive => {
                    vec!["Exchange is already activated.".to_string()]
                }
            },
            Self::Deactivated {
                chain_id,
                chain_label,
                display_name,
                outcome,
                ..
            } => match outcome {
                DeactivateOutcome::Deactivated => vec![format!(
                    "Deactivated {display_name} on {chain_label} (chain ID {chain_id})."
                )],
                DeactivateOutcome::AlreadyDeactivated => {
                    vec!["Exchange is already deactivated.".to_string()]
                }
                DeactivateOutcome::NoEntry => vec![format!(
                    "The database has no entry for {display_name} on {chain_label} \
                     (chain ID {chain_id})."
                )],
            },
            Self::Listed { rows } => rows
                .iter()
                .map(|row| {
                    format!(
                        "{} on {} (chain ID {}): {}",
                        row.display_name,
                        row.chain_label,
                        row.chain_id,
                        row.state.as_str()
                    )
                })
                .collect(),
        }
    }
}

/// The typed result of a `pool` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PoolReport {
    /// `pool update` advanced the chain.
    Updated {
        /// The chain advanced.
        chain_id: i64,
        /// The first block processed.
        from_block: u64,
        /// The last block advanced to.
        to_block: u64,
        /// Chunks committed.
        chunks_committed: usize,
        /// Pool rows written.
        total_pools_written: usize,
        /// Per-pool liquidity applies.
        total_liquidity_applies: usize,
    },
    /// `pool update` was cooperatively cancelled; committed chunks stay durable.
    UpdateCancelled {
        /// The chain.
        chain_id: i64,
    },
    /// `pool verify` compared the committed map against on-chain truth.
    Verified {
        /// The pool identifier.
        pool: String,
        /// The family.
        family: PoolFamily,
        /// The block the truth was read at.
        block_number: u64,
        /// The named divergences (empty = GREEN).
        divergences: Vec<degenbot_pool_updater::LiquidityDivergence>,
    },
}

impl PoolReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Updated {
                chain_id,
                from_block,
                to_block,
                chunks_committed,
                total_pools_written,
                total_liquidity_applies,
            } => vec![format!(
                "Chain {chain_id}: advanced {from_block}->{to_block} in {chunks_committed} \
                 chunks ({total_pools_written} pools written, {total_liquidity_applies} \
                 liquidity applies)."
            )],
            Self::UpdateCancelled { chain_id } => vec![format!(
                "Chain {chain_id}: cancelled (committed chunks stay durable)."
            )],
            Self::Verified {
                pool,
                family,
                block_number,
                divergences,
            } => verification_lines(pool, *family, *block_number, divergences),
        }
    }
}

/// The typed result of a `fleet` command (ADR-051 D6).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FleetReport {
    /// The live posture echo: the six `cordon_*` values plus `posture`,
    /// rendered as one compact JSON object with sorted keys (the Python
    /// `json.dumps(effective, sort_keys=True)` line).
    Posture {
        /// The rendered effective policy (`{}` when the host echoed none).
        effective: String,
    },
}

impl FleetReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Posture { effective } => vec![effective.clone()],
        }
    }
}

/// The typed result of a `path` command (ADR-051 D6).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathReport {
    /// `path add` enqueued the path.
    Added {
        /// The host's `detail` receipt.
        detail: String,
    },
    /// `path discover` completed a bounded sweep.
    Discovered {
        /// The host's `detail` receipt.
        detail: String,
    },
}

impl PathReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Added { detail } | Self::Discovered { detail } => vec![detail.clone()],
        }
    }
}

/// The typed result of a `strategy` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StrategyReport {
    /// `strategy list`: every declared facet.
    Listed {
        /// One descriptor per facet, in declaration order.
        rows: Vec<StrategyFacetDescriptor>,
    },
    /// `strategy show`: one facet's descriptor plus its activation posture.
    Shown {
        /// The facet descriptor.
        descriptor: StrategyFacetDescriptor,
        /// The facet's activation + endpoint posture (`None` when no config
        /// file could be read).
        activation: Option<crate::strategy::EndpointSummary>,
    },
    /// `strategy activate`: the facet was activated with the settled posture.
    Activated {
        /// The activated facet.
        facet: crate::strategy::StrategyFacet,
        /// The settled endpoint posture.
        summary: crate::strategy::EndpointSummary,
        /// Whether the write applies or an env var shadows it.
        outcome: crate::strategy::MutationOutcome,
    },
    /// `strategy deactivate`: the facet was deactivated.
    Deactivated {
        /// The deactivated facet.
        facet: crate::strategy::StrategyFacet,
        /// Whether the write applies or an env var shadows it.
        outcome: crate::strategy::MutationOutcome,
    },
    /// `strategy set`: a facet key's override was written.
    Set {
        /// The mutated facet.
        facet: crate::strategy::StrategyFacet,
        /// The written key's field name.
        key: &'static str,
        /// Whether the write applies or an env var shadows it.
        outcome: crate::strategy::MutationOutcome,
    },
    /// `strategy default` / `strategy remove`: the override was dropped so the
    /// schema default applies again.
    Defaulted {
        /// The mutated facet.
        facet: crate::strategy::StrategyFacet,
        /// The restored key's field name.
        key: &'static str,
    },
}

impl StrategyReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Listed { rows } => rows
                .iter()
                .map(|descriptor| {
                    format!(
                        "{} ({}) -> {} [{} declared key(s)]",
                        descriptor.facet.as_str(),
                        descriptor.trigger_kind,
                        descriptor.config_section,
                        descriptor.fields.len()
                    )
                })
                .collect(),
            Self::Shown {
                descriptor,
                activation,
            } => {
                let mut lines = vec![format!(
                    "{}: {} strategy",
                    descriptor.config_section, descriptor.trigger_kind
                )];
                lines.push(format!("  selector: {}", descriptor.facet.as_str()));
                if let Some(summary) = activation {
                    lines.push(format!("  posture: {}", posture_line(summary)));
                }
                if descriptor.fields.is_empty() {
                    lines.push("  declared keys: (none yet)".to_string());
                } else {
                    for (field, env) in descriptor.fields.iter().zip(&descriptor.envs) {
                        lines.push(format!("  {field} ({env})"));
                    }
                }
                lines
            }
            Self::Activated {
                facet,
                summary,
                outcome,
            } => vec![
                format!("activated strategy {}", facet.as_str()),
                format!("  endpoints: {}", posture_line(summary)),
                shadow_line(outcome),
            ],
            Self::Deactivated { facet, outcome } => vec![
                format!(
                    "deactivated strategy {} (recorded endpoints kept)",
                    facet.as_str()
                ),
                shadow_line(outcome),
            ],
            Self::Set {
                facet,
                key,
                outcome,
            } => vec![
                format!("set {}.{}", facet.config_section(), key),
                shadow_line(outcome),
            ],
            Self::Defaulted { facet, key } => vec![format!(
                "restored {}.{} to its declared default",
                facet.config_section(),
                key
            )],
        }
    }
}

/// One line describing a facet's settled endpoint posture.
fn posture_line(summary: &crate::strategy::EndpointSummary) -> String {
    match summary {
        crate::strategy::EndpointSummary::Inactive => "inactive".to_string(),
        crate::strategy::EndpointSummary::Unset => {
            "UNSET (activation requires --endpoints or --endpoints-default)".to_string()
        }
        crate::strategy::EndpointSummary::Default(urls) => {
            format!("default ({})", urls.join(", "))
        }
        crate::strategy::EndpointSummary::Explicit(urls) => urls.join(", "),
    }
}

/// The loud line when the env layer shadows a written key.
fn shadow_line(outcome: &crate::strategy::MutationOutcome) -> String {
    match outcome {
        crate::strategy::MutationOutcome::Applied => "  applies at load time".to_string(),
        crate::strategy::MutationOutcome::Shadowed { env } => {
            format!("  WARNING: {env} is set in the environment and will shadow this write")
        }
    }
}

/// The green / red `pool verify` text.
fn verification_lines(
    pool: &str,
    family: PoolFamily,
    block_number: u64,
    divergences: &[degenbot_pool_updater::LiquidityDivergence],
) -> Vec<String> {
    use degenbot_pool_updater::LiquidityDivergence;
    if divergences.is_empty() {
        return vec![format!(
            "GREEN: {} pool {pool} matches on-chain truth at block {block_number}.",
            family.as_str()
        )];
    }
    let mut lines = vec![format!(
        "RED: {} divergence(s) for {} pool {pool} at block {block_number}:",
        divergences.len(),
        family.as_str()
    )];
    for divergence in divergences {
        lines.push(match divergence {
            LiquidityDivergence::TickGross {
                tick,
                expected,
                actual,
            } => format!("  tick {tick}: TickGross expected={expected} actual={actual}"),
            LiquidityDivergence::TickNet {
                tick,
                expected,
                actual,
            } => format!("  tick {tick}: TickNet expected={expected} actual={actual}"),
            LiquidityDivergence::BitmapWord {
                word,
                expected,
                actual,
            } => format!("  word {word}: BitmapWord expected={expected} actual={actual}"),
            LiquidityDivergence::TickPresence {
                tick,
                stored,
                observed,
            } => format!("  tick {tick}: TickPresence stored={stored} observed={observed}"),
        });
    }
    lines
}

/// One `aave update` market's outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AaveUpdateOutcome {
    /// The market advanced.
    Advanced {
        /// First block processed.
        from_block: u64,
        /// Last block advanced to.
        to_block: u64,
        /// Chunks committed.
        chunks_committed: usize,
        /// Events applied.
        total_events_applied: usize,
    },
    /// The market's run was cooperatively cancelled.
    Cancelled,
    /// The market has no `last_update_block`; it is skipped (must be bootstrapped).
    NeedsBootstrap,
    /// `--dry-run`: the would-be advance, with nothing committed.
    DryRun {
        /// The market's `last_update_block`.
        last_update_block: i64,
        /// The resolved target (`None` = chain tip).
        to_block: Option<u64>,
    },
}

/// One `aave update` market row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AaveUpdateEntry {
    /// The chain.
    pub chain_id: i64,
    /// The market id.
    pub market_id: i64,
    /// The market name.
    pub market_name: String,
    /// The outcome.
    pub outcome: AaveUpdateOutcome,
}

/// One position row (scaled balance + token symbol).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AavePositionLine {
    /// The underlying token symbol (`Unknown` when unresolved).
    pub symbol: String,
    /// The scaled balance.
    pub balance: U256,
}

/// The typed result of an `aave` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AaveReport {
    /// `aave activate`.
    Activated {
        /// The chain id.
        chain_id: u64,
        /// The human chain label.
        chain_label: &'static str,
        /// The market id.
        market_id: i64,
        /// The on-chain market name.
        market_name: String,
        /// Whether the market was newly created.
        created: bool,
    },
    /// `aave deactivate`.
    Deactivated {
        /// The chain id.
        chain_id: u64,
        /// The market id, when a row was found.
        market_id: Option<i64>,
        /// The outcome.
        outcome: DeactivateOutcome,
    },
    /// `aave update`.
    Updated {
        /// Per-market outcomes.
        entries: Vec<AaveUpdateEntry>,
    },
    /// `aave position show`.
    Position {
        /// The user address (checksummed).
        user_address: String,
        /// The market name.
        market: String,
        /// The chain id.
        chain_id: u64,
        /// Collateral positions.
        collateral: Vec<AavePositionLine>,
        /// Debt positions.
        debt: Vec<AavePositionLine>,
    },
    /// `aave position show` found no market.
    PositionNoMarket {
        /// The market name.
        market: String,
        /// The chain id.
        chain_id: u64,
    },
    /// `aave position show` found no user row.
    PositionNoUser {
        /// The user address (checksummed).
        user_address: String,
        /// The market name.
        market: String,
        /// The chain id.
        chain_id: u64,
    },
}

impl AaveReport {
    /// The operator-facing lines for this report.
    #[must_use]
    pub fn render_lines(&self) -> Vec<String> {
        match self {
            Self::Activated {
                chain_id,
                chain_label,
                market_id,
                market_name,
                created,
            } => vec![
                format!("Activated Aave V3 on {chain_label} (chain ID {chain_id})."),
                format!("  Market: {market_name} (id={market_id}, created={created})."),
            ],
            Self::Deactivated {
                chain_id, outcome, ..
            } => match outcome {
                DeactivateOutcome::Deactivated => vec![format!(
                    "Deactivated Aave V3 on {} (chain ID {chain_id}).",
                    chain_label_for(*chain_id)
                )],
                DeactivateOutcome::AlreadyDeactivated => Vec::new(),
                DeactivateOutcome::NoEntry => {
                    vec![format!(
                        "The database has no entry for Aave V3 on {} (chain ID {chain_id}).",
                        chain_label_for(*chain_id)
                    )]
                }
            },
            Self::Updated { entries } => entries.iter().flat_map(entry_lines).collect(),
            Self::Position {
                user_address,
                market,
                chain_id,
                collateral,
                debt,
            } => position_lines(user_address, market, *chain_id, collateral, debt),
            Self::PositionNoMarket { market, chain_id } => {
                vec![format!(
                    "No market found with name '{market}' on chain {chain_id}."
                )]
            }
            Self::PositionNoUser {
                user_address,
                market,
                chain_id,
            } => vec![format!(
                "No Aave user found for address {user_address} in market '{market}' on chain \
                 {chain_id}."
            )],
        }
    }
}

/// The human chain label used in the aave report lines.
fn chain_label_for(chain_id: u64) -> String {
    match chain_id {
        1 => "Ethereum".to_string(),
        8453 => "Base".to_string(),
        other => other.to_string(),
    }
}

/// The lines for one `aave update` market.
fn entry_lines(entry: &AaveUpdateEntry) -> Vec<String> {
    let AaveUpdateEntry {
        chain_id,
        market_id,
        market_name,
        outcome,
    } = entry;
    match outcome {
        AaveUpdateOutcome::Advanced {
            from_block,
            to_block,
            chunks_committed,
            total_events_applied,
        } => vec![format!(
            "Chain {chain_id} market {market_id} ({market_name}): advanced {from_block}-> \
             {to_block} in {chunks_committed} chunks ({total_events_applied} events applied)."
        )],
        AaveUpdateOutcome::Cancelled => vec![format!(
            "Chain {chain_id} market {market_id}: cancelled (committed chunks stay durable)."
        )],
        AaveUpdateOutcome::NeedsBootstrap => vec![format!(
            "Chain {chain_id} market {market_id} ({market_name}): needs bootstrapping \
             (last_update_block is None); skipping. Bootstrap the stamp before running."
        )],
        AaveUpdateOutcome::DryRun {
            last_update_block,
            to_block,
        } => vec![format!(
            "Dry run: would advance chain {chain_id} market {market_id} ({market_name}) from \
             block {last_update_block} to {} (no changes committed).",
            render_opt_block(*to_block)
        )],
    }
}

/// Render an optional resolved block the way Python's `{value!r}` does.
fn render_opt_block(block: Option<u64>) -> String {
    block.map_or_else(|| "None".to_string(), |n| n.to_string())
}

/// The ported `aave position show` body.
fn position_lines(
    user_address: &str,
    market: &str,
    chain_id: u64,
    collateral: &[AavePositionLine],
    debt: &[AavePositionLine],
) -> Vec<String> {
    let mut lines = vec![
        format!("Aave V3 Positions for {user_address}"),
        format!("Market: {market} (Chain: {chain_id})"),
        "=".repeat(60),
    ];
    if collateral.is_empty() {
        lines.push("No collateral positions found.".to_string());
    } else {
        lines.push("Collateral Positions:".to_string());
        lines.push("-".repeat(60));
        lines.extend(
            collateral
                .iter()
                .map(|p| format!("  {}: {} (scaled)", p.symbol, p.balance)),
        );
    }
    if debt.is_empty() {
        lines.push("No debt positions found.".to_string());
    } else {
        lines.push("Debt Positions:".to_string());
        lines.push("-".repeat(60));
        lines.extend(
            debt.iter()
                .map(|p| format!("  {}: {} (scaled)", p.symbol, p.balance)),
        );
    }
    lines
}

/// The ported `heal` success / no-op text.
fn healed_lines(path: &std::path::Path, report: &HealReport) -> Vec<String> {
    if matches!(report.old_state, SchemaState::RustOwned { .. }) {
        return vec![format!(
            "Database at {} is already Rust-owned; heal is a no-op (no copy, no .bak).",
            path.display()
        )];
    }
    let total_rows: u64 = report.rows_copied.values().sum();
    let n_tables = report.rows_copied.len();
    let mut lines = vec![format!(
        "Healed database at {}: {total_rows} rows across {n_tables} tables copied; old DB \
         preserved at {}; new state: {}.",
        path.display(),
        report.bak_path.display(),
        schema_state_label(&report.new_state)
    )];
    if !report.warnings.is_empty() {
        lines.push(format!("Warnings: {}", report.warnings.join("; ")));
    }
    lines
}

/// The ported `database cutover --dry-run` line for `state`.
#[must_use]
pub fn cutover_dry_run_line(state: &SchemaState) -> String {
    let label = schema_state_label(state);
    match state {
        SchemaState::LegacyAlembic => format!(
            "Schema state: {label}. Would cutover from Alembic to Rust ownership (drop \
             `alembic_version`, stamp `_degenbot_db_schema_version`)."
        ),
        SchemaState::RustOwned { .. } => {
            format!("Schema state: {label}. Already Rust-owned — cutover is a no-op.")
        }
        SchemaState::FreshStandalone { .. } => {
            format!("Schema state: {label}. No legacy history — nothing to cutover.")
        }
        SchemaState::Unrecognized => {
            format!("Schema state: {label}. Unrecognized database (foreign file).")
        }
    }
}

/// The ported `database heal --dry-run` line for `state`.
#[must_use]
pub fn heal_dry_run_line(state: &SchemaState) -> String {
    let label = schema_state_label(state);
    match state {
        SchemaState::LegacyAlembic => format!(
            "Schema state: {label}. Would heal: rebuild at the Rust head schema, copy all \
             rows, drop alembic_version, stamp _degenbot_db_schema_version, atomic-swap with \
             a *.bak backup."
        ),
        SchemaState::RustOwned { .. } => {
            format!("Schema state: {label}. Already Rust-owned — heal is a no-op.")
        }
        SchemaState::FreshStandalone { .. } => format!(
            "Schema state: {label}. Empty file — heal produces a fresh RustOwned DB (0 rows \
             copied)."
        ),
        SchemaState::Unrecognized => {
            format!(
                "Schema state: {label}. Unrecognized database (foreign file) — heal would \
                 refuse."
            )
        }
    }
}

/// The Python-compatible label for a [`SchemaState`] (mirrors the
/// `db_inspect_schema_state` return values).
#[must_use]
pub fn schema_state_label(state: &SchemaState) -> &'static str {
    match state {
        SchemaState::LegacyAlembic => "legacy_alembic",
        SchemaState::FreshStandalone { .. } => "fresh_standalone",
        SchemaState::RustOwned { .. } => "rust_owned",
        SchemaState::Unrecognized => "unrecognized",
    }
}