atupa 0.1.1

atupa — Unified EVM + Stylus Execution Profiler CLI
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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
//! # atupa CLI
//!
//! Unified Ethereum + Arbitrum Stylus execution profiler.
//!
//! ## Usage
//!
//! ```text
//! atupa profile  --tx <HASH> [--rpc <URL>] [--out trace.svg] [--demo]
//! atupa capture  --tx <HASH> [--rpc <URL>] [--output summary|json|metric] [--file report.json]
//!               [--profile] [--etherscan-key <KEY>] [--studio]
//! atupa audit    --tx <HASH> [--rpc <URL>] [--protocol aave|lido]
//! atupa diff     --base <HASH> --target <HASH> [--rpc <URL>]
//! ```
//!
//! ## Standalone Usage
//! Atupa is designed to be used as a standalone CLI tool.

use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use colored::*;
use indicatif::{ProgressBar, ProgressStyle};
use std::time::Duration;

use atupa_aave::AaveDeepTracer;
use atupa_core::TraceStep;
use atupa_core::config::AtupaConfig;
use atupa_lido::LidoDeepTracer;
use atupa_nitro::{NitroClient, StitchedReport, VmKind};
use atupa_output::SvgGenerator;
use atupa_parser::Parser as TraceParser;
use atupa_parser::aggregator::Aggregator;
use atupa_rpc::{EthClient, RawStructLog};

mod init;
mod studio;
mod thresholds;

use thresholds::AtupaConfigToml;
// ─── CLI Definition ────────────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name = "atupa",
    bin_name = "atupa",
    about = "🏮 Atupa — Unified Ethereum & Stylus Execution Profiler",
    long_about = "\
Inspect, profile, and audit transactions across the full Arbitrum Nitro\n\
dual-VM stack (EVM + Stylus WASM). Part of the One Block infrastructure suite.\n\
SOURCE: https://github.com/One-Block-Org/Atupa",
    version
)]
struct Cli {
    /// Arbitrum / Ethereum RPC endpoint (or set ATUPA_RPC_URL)
    #[arg(short, long, global = true, value_name = "URL")]
    rpc: Option<String>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Generate a visual SVG flamegraph for any EVM transaction
    Profile {
        /// Transaction hash (0x-prefixed); omit when using --demo
        #[arg(short, long, value_name = "TX_HASH", default_value = "")]
        tx: String,

        /// Run an offline demo trace (no RPC required)
        #[arg(long, default_value_t = false)]
        demo: bool,

        /// Output path for the SVG (default: profile_<tx>.svg)
        #[arg(short, long, value_name = "FILE")]
        out: Option<String>,

        /// Etherscan API key for contract name resolution
        #[arg(long, value_name = "KEY")]
        etherscan_key: Option<String>,
    },

    /// Capture a unified EVM + Stylus execution trace (Arbitrum Nitro).
    ///
    /// Add --profile to also generate an SVG flamegraph from the same RPC call.
    /// Add --studio  to automatically launch Atupa Studio with the report loaded.
    Capture {
        /// Transaction hash to profile (0x-prefixed)
        #[arg(short, long, value_name = "TX_HASH")]
        tx: String,

        /// Output format for the JSON/summary report
        #[arg(short, long, value_enum, default_value_t = OutputFormat::Summary)]
        output: OutputFormat,

        /// Write report to a file instead of stdout
        #[arg(short = 'f', long, value_name = "FILE")]
        file: Option<String>,

        /// Also generate an SVG flamegraph (reuses the same RPC trace)
        #[arg(long, default_value_t = false)]
        profile: bool,

        /// Etherscan API key for contract name resolution
        #[arg(long, value_name = "KEY")]
        etherscan_key: Option<String>,

        /// Launch Atupa Studio after capture and open it in the browser
        #[arg(long, default_value_t = false)]
        studio: bool,
    },

    /// Protocol-aware execution auditing (Aave v3/GHO, Lido)
    Audit {
        /// Transaction hash to audit (0x-prefixed)
        #[arg(short, long, value_name = "TX_HASH")]
        tx: String,

        /// Protocol adapter to apply
        #[arg(short, long, value_enum, default_value_t = Protocol::Aave)]
        protocol: Protocol,
    },

    /// Compare the execution cost of two transactions
    Diff {
        /// Base transaction hash (0x-prefixed)
        #[arg(short, long, value_name = "BASE_TX")]
        base: String,

        /// Target transaction hash (0x-prefixed)
        #[arg(short, long, value_name = "TARGET_TX")]
        target: String,

        /// Simple mode override: Fail CI if gas increases by > X%
        #[arg(long, value_name = "PERCENT")]
        threshold: Option<f64>,

        /// Path to atupa.toml (defaults to looking in CWD)
        #[arg(long, value_name = "FILE")]
        config: Option<String>,

        /// Generate artifacts/diff/report.md for GitHub PRs
        #[arg(long, default_value_t = false)]
        markdown: bool,

        /// Generate visual diff flamegraph in artifacts/diff/
        #[arg(long, default_value_t = false)]
        svg: bool,

        /// Output format (summary | json | markdown)
        #[arg(short, long, value_enum, default_value_t = OutputFormat::Summary)]
        output: OutputFormat,

        /// Optional: Run DeepTracer on both and diff heuristics
        #[arg(short, long, value_enum)]
        protocol: Option<Protocol>,
    },

    /// Launch Atupa Studio — the local web visualizer for trace reports
    Studio {
        /// Port for the dev server (default: 5173)
        #[arg(short, long, default_value_t = 5173)]
        port: u16,

        /// Path to the studio directory (overrides auto-detection)
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,

        /// Open the browser automatically after the server starts
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        open: bool,
    },

    /// Scaffold Atupa config, GitHub Actions workflow, and a profile script
    ///
    /// Run this once in a new repository to get started.
    /// Detects Foundry, Hardhat, or Stylus projects automatically.
    Init {
        /// Overwrite existing files
        #[arg(long, default_value_t = false)]
        force: bool,
    },
}

#[derive(Clone, ValueEnum, Debug, PartialEq, Eq)]
enum OutputFormat {
    /// Human-readable terminal summary (default)
    Summary,
    /// Full step-by-step JSON — suitable for CI assertions and tooling
    Json,
    /// Emit only the numeric unified cost (gas-equiv) — ideal for scripting
    Metric,
}

#[derive(Clone, ValueEnum, Debug)]
enum Protocol {
    /// Aave v3 + GHO stablecoin protocol adapters
    Aave,
    /// Lido stETH execution resilience (Phase II roadmap)
    Lido,
}

// ─── Entry Point ──────────────────────────────────────────────────────────────

#[tokio::main]
async fn main() -> Result<()> {
    let args = std::env::args_os();

    env_logger::builder()
        .filter_level(log::LevelFilter::Warn)
        .parse_default_env()
        .init();

    let cli = Cli::parse_from(args);
    let mut config = AtupaConfig::load();

    if let Some(r) = cli.rpc {
        config.rpc_url = r;
    }

    print_banner();

    match cli.command {
        Commands::Profile {
            tx,
            demo,
            out,
            etherscan_key,
        } => {
            if let Some(key) = etherscan_key {
                config.etherscan_key = Some(key);
            }
            cmd_profile(&config, &tx, demo, out).await?;
        }
        Commands::Capture {
            tx,
            output,
            file,
            profile,
            etherscan_key,
            studio,
        } => {
            if let Some(key) = etherscan_key {
                config.etherscan_key = Some(key);
            }
            let report_path = cmd_capture(&config, &tx, output, file, profile).await?;
            if studio {
                // Pass the generated report path to Studio for auto-load
                cmd_studio(&config, config.studio_port, true, report_path).await?;
            }
        }
        Commands::Audit { tx, protocol } => {
            cmd_audit(&config, &tx, protocol).await?;
        }
        Commands::Diff {
            base,
            target,
            threshold,
            config: diff_config,
            markdown,
            svg,
            protocol,
            output,
        } => {
            cmd_diff(
                &config,
                &base,
                &target,
                threshold,
                diff_config,
                markdown,
                svg,
                output,
                protocol,
            )
            .await?;
        }
        Commands::Studio { port, dir, open } => {
            if let Some(d) = dir {
                config.studio_dir = Some(std::path::PathBuf::from(d));
            }
            config.studio_port = port;
            cmd_studio(&config, port, open, None).await?;
        }
        Commands::Init { force } => {
            init::execute_init(init::InitArgs { force })?;
        }
    }

    Ok(())
}

// ─── Profile Command ──────────────────────────────────────────────────────────

async fn cmd_profile(
    config: &AtupaConfig,
    tx: &str,
    demo: bool,
    out: Option<String>,
) -> Result<()> {
    if !demo && tx.is_empty() {
        anyhow::bail!(
            "You must provide --tx <HASH> or run with --demo.\n\
             Example: atupa profile --demo"
        );
    }

    let display = if demo { "demo" } else { tx };
    eprintln!("{} {}", "→ Profiling:".bold(), display.cyan());
    eprintln!("{} {}\n", "→ Endpoint: ".bold(), config.rpc_url.dimmed());

    // Route output through the standard artifacts directory (same as capture)
    let svg_path = resolve_artifact_path(out, "profile", tx, "svg");

    let (out_path, network) = atupa::execute_profile(
        tx,
        &config.rpc_url,
        demo,
        Some(svg_path),
        config.etherscan_key.clone(),
    )
    .await
    .context("Profile command failed")?;

    eprintln!();
    eprintln!(
        "  {} ({})",
        "PROFILE COMPLETE".bold().underline(),
        network.cyan()
    );
    let div = "".repeat(40).dimmed().to_string();
    eprintln!("{div}");
    eprintln!(
        "  {:<24} {}",
        "SVG saved to:".bold(),
        out_path.green().bold()
    );
    eprintln!("{div}");
    Ok(())
}

// ─── Capture Command ──────────────────────────────────────────────────────────

async fn cmd_capture(
    config: &AtupaConfig,
    tx: &str,
    format: OutputFormat,
    file: Option<String>,
    generate_profile: bool,
) -> Result<Option<String>> {
    let tx = normalise_hash(tx);
    eprintln!("{} {}", "→ Transaction:".bold(), tx.cyan());
    eprintln!("{} {}\n", "→ Endpoint:   ".bold(), config.rpc_url.dimmed());

    // Phase 1: fetch ──────────────────────────────────────────────────────────
    let pb = spinner("Detecting network and fetching execution trace…");
    let client = NitroClient::new(config.rpc_url.clone());

    let mut report = client
        .trace_transaction(&tx)
        .await
        .context("Failed to fetch trace — ensure the RPC endpoint is valid and accessible.")?;

    let network_name = get_network_name(report.chain_id);
    pb.finish_with_message(format!(
        "{} Captured trace from {} ({} EVM steps{} )",
        "".green().bold(),
        network_name.cyan().bold(),
        evm_count(&report).to_string().green(),
        if report.total_stylus_ink > 0 {
            format!(
                " + {} Stylus HostIOs",
                report.stylus_steps().len().to_string().yellow()
            )
        } else {
            "".into()
        }
    ));

    // Phase 1b: fetch receipt for on-chain gasUsed (non-fatal) ──────────────────
    let eth_client = EthClient::new(config.rpc_url.clone());
    report.on_chain_gas_used = eth_client.get_gas_used(&tx).await;

    // Phase 1.5: resolve contract names ─────────────────────────────────────────
    if let Some(key) = config.etherscan_key.clone() {
        let pb_names = spinner("Resolving contract names via Etherscan…");
        let resolver = atupa_rpc::etherscan::EtherscanResolver::new(Some(key), report.chain_id);

        let mut addresses = std::collections::HashSet::new();
        for step in &report.steps {
            if let Some(evm) = &step.evm
                && (evm.op.contains("CALL") || evm.op.contains("CREATE"))
                && let Some(stack) = &evm.stack
                && stack.len() >= 2
            {
                let hex_addr = &stack[stack.len() - 2];
                let clean_hex = hex_addr.trim_start_matches("0x");
                let padded = format!("{:0>40}", clean_hex);
                let extracted = &padded[padded.len() - 40..];
                addresses.insert(format!("0x{}", extracted));
            }
        }

        for addr in addresses {
            if let Some(name) = resolver.resolve_contract_name(&addr).await {
                report.resolved_names.insert(addr, name);
            }
        }
        pb_names.finish_with_message(format!(
            "{} Resolved {} contract name(s) via Etherscan.",
            "".green().bold(),
            report.resolved_names.len().to_string().cyan().bold()
        ));
    }

    // Phase 2: optional Flamegraph SVG (built from already-fetched report — no second RPC call) ──
    let mut svg_path: Option<String> = None;
    if generate_profile {
        let pb_svg = spinner("Generating SVG flamegraph…");

        // Convert report steps → collapsed stacks → SVG (zero extra RPC calls)
        let trace_steps: Vec<atupa_core::TraceStep> =
            report.steps.iter().map(|s| s.to_trace_step()).collect();
        let normalized = TraceParser::normalize_raw(trace_steps);
        let stacks = Aggregator::build_collapsed_stacks(&normalized);
        let svg = SvgGenerator::generate_flamegraph(&stacks)
            .context("SVG flamegraph generation failed")?;

        let svg_suggestion = file.as_ref().map(|f| {
            if f.ends_with(".json") {
                f.trim_end_matches(".json").to_string() + ".svg"
            } else {
                f.to_string() + ".svg"
            }
        });
        let svg_out = resolve_artifact_path(svg_suggestion, "capture", &tx, "svg");
        std::fs::write(&svg_out, svg)
            .with_context(|| format!("Failed to write SVG to '{svg_out}'"))?;

        pb_svg.finish_with_message(format!(
            "{} SVG saved → {}",
            "".green().bold(),
            svg_out.green().bold()
        ));
        svg_path = Some(svg_out);
    }

    // Phase 3: render report ──────────────────────────────────────────────────
    let pb2 = spinner("Rendering report…");
    let summary_text = render_capture_summary(&report);

    let rendered = match format {
        OutputFormat::Summary => summary_text.clone(),
        OutputFormat::Json => serde_json::to_string_pretty(&report)?,
        OutputFormat::Metric => format!("{:.4}", report.total_unified_cost),
    };
    pb2.finish_with_message(format!("{} Report ready.", "".green().bold()));

    eprintln!();
    println!("{}", summary_text);
    eprintln!();

    // Phase 4: output ─────────────────────────────────────────────────────────
    let report_path = resolve_artifact_path(file, "capture", &tx, "json");

    std::fs::write(&report_path, &rendered)
        .with_context(|| format!("Failed to write report to '{report_path}'"))?;

    eprintln!(
        "{} Report saved to {}",
        "".green().bold(),
        report_path.cyan().bold()
    );

    if let Some(ref svg) = svg_path {
        eprintln!(
            "{} SVG profile saved to {}",
            "".green().bold(),
            svg.cyan().bold()
        );
    }

    Ok(Some(report_path))
}

// ─── Audit Command ────────────────────────────────────────────────────────────

async fn cmd_audit(config: &AtupaConfig, tx: &str, protocol: Protocol) -> Result<()> {
    let tx = normalise_hash(tx);
    let label = match protocol {
        Protocol::Aave => "Aave v3 + GHO",
        Protocol::Lido => "Lido stETH",
    };

    eprintln!(
        "{} {} audit for {}",
        "".bold(),
        label.yellow().bold(),
        tx.cyan()
    );
    eprintln!("{} {}\n", "→ Endpoint:".bold(), config.rpc_url.dimmed());

    let eth_client = EthClient::new(config.rpc_url.clone());
    let client = NitroClient::new(config.rpc_url.clone());

    // Fetch the top-level calldata selector (non-fatal) — gives us the real function being called
    let top_level_selector = eth_client
        .get_transaction_input(&tx)
        .await
        .and_then(|input| EthClient::selector_from_input(&input));

    let pb = spinner(&format!("Fetching trace for {label} audit…"));

    let report = client
        .trace_transaction(&tx)
        .await
        .context("Failed to fetch trace — is the Arbitrum node running?")?;

    pb.finish_with_message(format!(
        "{} Trace captured ({} unified steps).",
        "".green().bold(),
        report.steps.len()
    ));

    match protocol {
        Protocol::Aave => {
            let pb2 = spinner("Applying Aave v3 + GHO protocol adapter…");

            let trace_steps: Vec<TraceStep> = report
                .steps
                .iter()
                .filter(|s| s.vm == VmKind::Evm)
                .filter_map(|s| s.evm.as_ref())
                .map(bridge_raw_to_trace_step)
                .collect();

            let tracer = AaveDeepTracer::new();
            let liq = tracer
                .analyze_liquidation(&tx, &trace_steps)
                .context("Aave adapter failed")?;

            pb2.finish_with_message(format!("{} Aave v3 adapter complete.", "".green().bold()));
            eprintln!();
            print_aave_report(&liq, &report, top_level_selector.as_deref());
        }
        Protocol::Lido => {
            let pb2 = spinner("Applying Lido stETH protocol adapter…");

            let trace_steps: Vec<TraceStep> = report
                .steps
                .iter()
                .filter(|s| s.vm == VmKind::Evm)
                .filter_map(|s| s.evm.as_ref())
                .map(bridge_raw_to_trace_step)
                .collect();

            let tracer = LidoDeepTracer::new();
            let res = tracer
                .analyze_staking(&tx, &trace_steps)
                .context("Lido adapter failed")?;

            pb2.finish_with_message(format!(
                "{} Lido stETH adapter complete.",
                "".green().bold()
            ));
            eprintln!();
            print_lido_report(&res, &report, top_level_selector.as_deref());
        }
    }

    Ok(())
}

// ─── Diff Command ─────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
#[allow(clippy::collapsible_if)]
async fn cmd_diff(
    config: &AtupaConfig,
    base: &str,
    target: &str,
    threshold: Option<f64>,
    diff_config: Option<String>,
    markdown: bool,
    svg: bool,
    output_format: OutputFormat,
    protocol: Option<Protocol>,
) -> Result<()> {
    let base = normalise_hash(base);
    let target = normalise_hash(target);

    eprintln!(
        "{} {} {} {}",
        "→ Base:  ".bold(),
        base.cyan(),
        "Target:".bold(),
        target.yellow()
    );
    eprintln!("{} {}\n", "→ Endpoint:".bold(), config.rpc_url.dimmed());

    let client = NitroClient::new(config.rpc_url.clone());
    let eth_client = EthClient::new(config.rpc_url.clone());

    let pb = spinner("Fetching both traces and receipts concurrently…");

    // Fetch traces
    let (base_report, target_report) = tokio::try_join!(
        client.trace_transaction(&base),
        client.trace_transaction(&target),
    )
    .context("Failed to fetch one or both traces")?;

    // Fetch receipts for actual gas used
    let (base_receipt_gas, target_receipt_gas) = tokio::join!(
        eth_client.get_gas_used(&base),
        eth_client.get_gas_used(&target),
    );

    pb.finish_with_message(format!("{} Both traces fetched.", "".green().bold()));
    eprintln!();

    // Cost deltas
    let base_unified_cost = base_report.total_unified_cost;
    let target_unified_cost = target_report.total_unified_cost;
    let unified_delta = target_unified_cost - base_unified_cost;
    let unified_pct = if base_unified_cost > 0.0 {
        unified_delta / base_unified_cost * 100.0
    } else {
        0.0
    };

    let base_total_gas = base_receipt_gas.unwrap_or(base_unified_cost as u64);
    let target_total_gas = target_receipt_gas.unwrap_or(target_unified_cost as u64);
    let total_gas_delta = target_total_gas as f64 - base_total_gas as f64;
    let total_gas_pct = if base_total_gas > 0 {
        total_gas_delta / base_total_gas as f64 * 100.0
    } else {
        0.0
    };

    let base_intrinsic = base_total_gas.saturating_sub(base_unified_cost as u64);
    let target_intrinsic = target_total_gas.saturating_sub(target_unified_cost as u64);

    let div = "".repeat(70).dimmed().to_string();

    println!("{}", "  EXECUTION DIFF".bold().underline());
    println!("{div}");

    // Print Table Header
    println!(
        "  {:<25} {:<15} {:<15} {}",
        "Metric".bold(),
        "Base".bold(),
        "Target".bold(),
        "Delta".bold()
    );
    println!("{div}");

    let colorize_delta = |delta: f64, pct: f64| -> String {
        let sign = if delta >= 0.0 { "+" } else { "" };
        if delta > 0.0 {
            format!("{sign}{delta:.0} ({sign}{pct:.1}%)")
                .red()
                .to_string()
        } else if delta < 0.0 {
            format!("{sign}{delta:.0} ({sign}{pct:.1}%)")
                .green()
                .to_string()
        } else {
            format!("{sign}{delta:.0} ({sign}{pct:.1}%)")
                .dimmed()
                .to_string()
        }
    };

    println!(
        "  {:<25} {:<15} {:<15} {}",
        "Total On-Chain Gas:",
        base_total_gas.to_string().green(),
        target_total_gas.to_string().yellow(),
        colorize_delta(total_gas_delta, total_gas_pct)
    );

    println!(
        "  {:<25} {:<15} {:<15} {}",
        "↳ Execution Gas (EVM):",
        base_unified_cost.to_string().cyan(),
        target_unified_cost.to_string().cyan(),
        colorize_delta(unified_delta, unified_pct)
    );

    let intrinsic_delta = target_intrinsic as f64 - base_intrinsic as f64;
    let intrinsic_pct = if base_intrinsic > 0 {
        intrinsic_delta / base_intrinsic as f64 * 100.0
    } else {
        0.0
    };
    println!(
        "  {:<25} {:<15} {:<15} {}",
        "↳ Intrinsic Gas:",
        base_intrinsic.to_string().dimmed(),
        target_intrinsic.to_string().dimmed(),
        colorize_delta(intrinsic_delta, intrinsic_pct)
    );

    println!("{div}");

    // Step count comparison
    let base_evm = evm_count(&base_report);
    let tgt_evm = evm_count(&target_report);
    let evm_delta = tgt_evm as f64 - base_evm as f64;
    let evm_pct = if base_evm > 0 {
        evm_delta / base_evm as f64 * 100.0
    } else {
        0.0
    };
    println!(
        "  {:<25} {:<15} {:<15} {}",
        "EVM Steps:",
        base_evm.to_string().green(),
        tgt_evm.to_string().yellow(),
        colorize_delta(evm_delta, evm_pct)
    );

    let base_stylus = base_report.stylus_steps().len();
    let tgt_stylus = target_report.stylus_steps().len();
    let stylus_delta = tgt_stylus as f64 - base_stylus as f64;
    let stylus_pct = if base_stylus > 0 {
        stylus_delta / base_stylus as f64 * 100.0
    } else {
        0.0
    };
    println!(
        "  {:<25} {:<15} {:<15} {}",
        "Stylus Cross-VM Calls:",
        base_stylus.to_string().green(),
        tgt_stylus.to_string().yellow(),
        colorize_delta(stylus_delta, stylus_pct)
    );
    println!("{div}");

    // ── Protocol Deep Diff (opt-in) ──────────────────────────────────────────
    let mut proto_diff_rows: Vec<atupa_core::DiffRow> = Vec::new();
    let mut proto_name = String::new();

    if let Some(ref proto) = protocol {
        let base_steps: Vec<TraceStep> = base_report
            .steps
            .iter()
            .map(|s| s.to_trace_step())
            .collect();
        let target_steps: Vec<TraceStep> = target_report
            .steps
            .iter()
            .map(|s| s.to_trace_step())
            .collect();

        let proto_report = match proto {
            Protocol::Aave => {
                let tracer = AaveDeepTracer::new();
                tracer.diff_reports(&base, &base_steps, &target, &target_steps)
            }
            Protocol::Lido => {
                let tracer = LidoDeepTracer::new();
                tracer.diff_reports(&base, &base_steps, &target, &target_steps)
            }
        };

        match proto_report {
            Ok(report) => {
                proto_name = report.protocol.clone();
                let proto_div = "".repeat(70).dimmed().to_string();
                println!(
                    "\n  {} DEEP DIFF",
                    proto_name.to_uppercase().bold().underline()
                );
                println!("{proto_div}");
                println!(
                    "  {:<28} {:<15} {:<15} {}",
                    "Metric".bold(),
                    "Base".bold(),
                    "Target".bold(),
                    "Delta".bold()
                );
                println!("{proto_div}");

                for row in &report.rows {
                    let sign = if row.delta >= 0.0 { "+" } else { "" };
                    let delta_str = format!("{sign}{:.0} ({sign}{:.1}%)", row.delta, row.pct);
                    let delta_colored = if row.delta == 0.0 {
                        delta_str.dimmed().to_string()
                    } else if (row.delta > 0.0) == row.higher_is_worse {
                        delta_str.red().to_string() // bad change
                    } else {
                        delta_str.green().to_string() // good change
                    };
                    println!(
                        "  {:<28} {:<15} {:<15} {}",
                        row.metric,
                        row.base.to_string().dimmed(),
                        row.target.to_string().dimmed(),
                        delta_colored
                    );
                    proto_diff_rows.push(row.clone());
                }
                println!("{proto_div}");
            }
            Err(e) => {
                eprintln!("  ⚠ Protocol deep diff skipped: {e}");
            }
        }
    }

    let format_plain_delta = |delta: f64, pct: f64| -> String {
        let sign = if delta >= 0.0 { "+" } else { "" };
        format!("{sign}{delta:.0} ({sign}{pct:.1}%)")
    };

    if markdown {
        let md = format!(
            "## 🏮 Atupa Gas Regression Report\n\n\
            | Metric | Base | Target | Delta |\n\
            |--------|------|--------|-------|\n\
            | **Total Gas** | {} | {} | {} |\n\
            | **Execution Gas** | {} | {} | {} |\n\
            | **EVM Steps** | {} | {} | {} |\n\
            | **Stylus Calls** | {} | {} | {} |\n\n\
            *Profiled via Atupa Unified Tracer*\n",
            base_total_gas,
            target_total_gas,
            format_plain_delta(total_gas_delta, total_gas_pct),
            base_unified_cost,
            target_unified_cost,
            format_plain_delta(unified_delta, unified_pct),
            base_evm,
            tgt_evm,
            format_plain_delta(evm_delta, evm_pct),
            base_stylus,
            tgt_stylus,
            format_plain_delta(stylus_delta, stylus_pct)
        );
        let out_path = format!("artifacts/diff/{}_vs_{}.md", &base[..10], &target[..10]);
        std::fs::create_dir_all("artifacts/diff").ok();

        // Append protocol deep diff to markdown if available
        let proto_section = if !proto_diff_rows.is_empty() {
            let mut section = format!("\n### 🔬 {} Protocol Deep Diff\n\n", proto_name);
            section.push_str("| Metric | Base | Target | Delta |\n");
            section.push_str("|--------|------|--------|-------|\n");
            for row in &proto_diff_rows {
                let sign = if row.delta >= 0.0 { "+" } else { "" };
                let emoji = if row.delta == 0.0 {
                    ""
                } else if (row.delta > 0.0) == row.higher_is_worse {
                    "🔴 "
                } else {
                    "🟢 "
                };
                section.push_str(&format!(
                    "| **{}** | {} | {} | {}{}{:.0} ({}{:.1}%) |\n",
                    row.metric, row.base, row.target, emoji, sign, row.delta, sign, row.pct
                ));
            }
            section
        } else {
            String::new()
        };

        std::fs::write(&out_path, md + &proto_section).context("Failed to write markdown diff")?;
        println!("  📝 Markdown report written to {}", out_path.cyan());
    }

    if svg {
        let base_trace_steps: Vec<atupa_core::TraceStep> = base_report
            .steps
            .iter()
            .map(|s| s.to_trace_step())
            .collect();
        let base_normalized = TraceParser::normalize_raw(base_trace_steps);
        let base_stacks = Aggregator::build_collapsed_stacks(&base_normalized);

        let target_trace_steps: Vec<atupa_core::TraceStep> = target_report
            .steps
            .iter()
            .map(|s| s.to_trace_step())
            .collect();
        let target_normalized = TraceParser::normalize_raw(target_trace_steps);
        let target_stacks = Aggregator::build_collapsed_stacks(&target_normalized);

        let svg_content = atupa_output::generate_diff_flamegraph(&base_stacks, &target_stacks)?;
        let svg_path = format!("artifacts/diff/{}_vs_{}.svg", &base[..10], &target[..10]);
        std::fs::create_dir_all("artifacts/diff").ok();
        std::fs::write(&svg_path, svg_content).context("Failed to write diff flamegraph SVG")?;
        println!("  🔥 Visual diff flamegraph written to {}", svg_path.cyan());
    }

    // Threshold Engine Evaluation
    let mut failures = Vec::new();

    let config_toml = if let Some(path) = diff_config {
        AtupaConfigToml::load(std::path::Path::new(&path)).ok()
    } else {
        AtupaConfigToml::auto_load()
    };

    if let Some(t) = threshold {
        // Simple Mode override
        if total_gas_pct > t {
            failures.push(format!(
                "Total Gas increased by {:.1}% (limit: {:.1}%)",
                total_gas_pct, t
            ));
        }
    } else if let Some(ref cfg) = config_toml {
        // TOML Config evaluation
        if let Some(diff_cfg) = &cfg.diff {
            if let Some(max_total) = diff_cfg.max_total_gas_increase_percent {
                if total_gas_pct > max_total {
                    failures.push(format!(
                        "Total Gas increased by {:.1}% (limit: {:.1}%)",
                        total_gas_pct, max_total
                    ));
                }
            }
            if let Some(max_exec) = diff_cfg.max_execution_gas_increase_percent {
                if unified_pct > max_exec {
                    failures.push(format!(
                        "Execution Gas increased by {:.1}% (limit: {:.1}%)",
                        unified_pct, max_exec
                    ));
                }
            }
            if let Some(max_evm) = diff_cfg.max_evm_steps_increase {
                if evm_delta > max_evm as f64 {
                    failures.push(format!(
                        "EVM Steps increased by {:.0} (limit: {})",
                        evm_delta, max_evm
                    ));
                }
            }
            if let Some(max_stylus) = diff_cfg.max_stylus_calls_increase {
                if stylus_delta > max_stylus as f64 {
                    failures.push(format!(
                        "Stylus Calls increased by {:.0} (limit: {})",
                        stylus_delta, max_stylus
                    ));
                }
            }
        }
    }

    // Final Output Handling
    if output_format == OutputFormat::Json {
        let diff_report = serde_json::json!({
            "type": "diff",
            "protocol": protocol.map(|p| format!("{:?}", p)),
            "base": {
                "tx_hash": base,
                "report": base_report,
            },
            "target": {
                "tx_hash": target,
                "report": target_report,
            },
            "metrics": {
                "base_total_gas": base_total_gas,
                "target_total_gas": target_total_gas,
                "gas_delta": total_gas_delta,
                "gas_pct": total_gas_pct,
                "base_unified_cost": base_unified_cost,
                "target_unified_cost": target_unified_cost,
                "unified_delta": unified_delta,
                "unified_pct": unified_pct,
            }
        });
        println!("{}", serde_json::to_string_pretty(&diff_report)?);
    } else {
        if !failures.is_empty() {
            println!("\n  {}", "❌ [FAILED] Regression detected:".red().bold());
            for f in failures.iter() {
                println!("     - {}", f.red());
            }
        } else if threshold.is_some() || config_toml.is_some() {
            println!(
                "\n  {} Execution cost within acceptable limits.",
                "✅ [PASSED]".green().bold()
            );
        }
    }

    if !failures.is_empty() {
        return Err(anyhow::anyhow!("Gas regression thresholds exceeded"));
    }

    Ok(())
}

// ─── Studio Command ───────────────────────────────────────────────────────────

async fn cmd_studio(
    _config: &AtupaConfig,
    port: u16,
    launch_browser: bool,
    report_path: Option<String>,
) -> Result<()> {
    // 1. Read report if provided
    let report_content = if let Some(path) = report_path.as_ref() {
        Some(std::fs::read_to_string(path).context("Failed to read report file for Studio")?)
    } else {
        None
    };

    // 2. Prepare the server
    let server = studio::StudioServer::new(report_content);
    let mut url = format!("http://localhost:{port}/");
    if report_path.is_some() {
        url += "?auto=true";
    }

    eprintln!("{} Launching Atupa Studio...", "".bold().cyan());

    // Spawn server in background
    let server_handle = tokio::spawn(async move {
        if let Err(e) = server.start(port).await {
            eprintln!("\n{} Studio server error: {e}", "".red().bold());
        }
    });

    // Wait for the port to be active
    let addr = format!("127.0.0.1:{port}");
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while std::net::TcpStream::connect(&addr).is_err() {
        if std::time::Instant::now() > deadline {
            anyhow::bail!("Studio server failed to start on port {port} within 5s.");
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    eprintln!(
        "{} Studio ready at {}",
        "".green().bold(),
        url.cyan().bold()
    );

    // 3. Open browser
    if launch_browser && let Err(e) = open::that(&url) {
        eprintln!("{} Could not open browser: {e}", "".yellow());
    }

    // 4. Footer info
    if let Some(path) = report_path {
        eprintln!(
            "\n  {} Report loaded: {}\n  The Studio has automatically opened this report.",
            "".green().bold(),
            path.cyan().bold(),
        );
    }
    eprintln!("{}\n", "  Press Ctrl+C to stop the Studio server.".dimmed());

    // Keep the main thread alive while the server runs
    let _ = server_handle.await;
    Ok(())
}

// ─── Banner & Rendering ───────────────────────────────────────────────────────

fn print_banner() {
    eprintln!(
        "{}",
        "╔════════════════════════════════════════════╗".dimmed()
    );
    eprintln!(
        "{} {} {}",
        "".dimmed(),
        " 🏮  ATUPA  ·  Unified Execution Profiler  ".bold(),
        "".dimmed()
    );
    eprintln!(
        "{}",
        "╚════════════════════════════════════════════╝".dimmed()
    );
    eprintln!();
}

fn hostio_category_color(label: &str) -> &'static str {
    match label {
        "storage_flush_cache" | "storage_store_bytes32" => "\x1b[31;1m",
        "storage_load_bytes32" | "storage_cache_bytes32" => "\x1b[33m",
        "native_keccak256" => "\x1b[35m",
        "read_args" | "write_result" | "pay_for_memory_grow" => "\x1b[32m",
        "msg_sender" | "msg_value" | "msg_reentrant" | "emit_log" | "account_balance"
        | "block_hash" => "\x1b[36m",
        "call" | "static_call" | "delegate_call" | "create" => "\x1b[34m",
        _ => "\x1b[90m",
    }
}

fn render_capture_summary(report: &StitchedReport) -> String {
    const RESET: &str = "\x1b[0m";
    let div = "".repeat(56).dimmed().to_string();
    let wide_div = "".repeat(72);
    let mut out = String::new();

    out += &format!(
        "  {} ({})\n",
        "UNIFIED EXECUTION SUMMARY".bold().underline(),
        get_network_name(report.chain_id).cyan()
    );
    out += &format!("{div}\n");

    // ── Gas totals with Execution vs Intrinsic split ───────────────────────────────
    if let Some(on_chain) = report.on_chain_gas_used {
        let execution_gas = report.total_evm_gas;
        let intrinsic_gas = on_chain.saturating_sub(execution_gas);
        out += &format!(
            "  {:<34} {}\n",
            "Total Gas Used (on-chain):".bold(),
            on_chain.to_string().green().bold()
        );
        out += &format!(
            "  {:<34} {}\n",
            "  ├─ Execution:".dimmed(),
            execution_gas.to_string().green()
        );
        out += &format!(
            "  {:<34} {}\n",
            "  └─ Intrinsic (base + calldata):".dimmed(),
            intrinsic_gas.to_string().yellow()
        );
    } else {
        out += &format!(
            "  {:<34} {}\n",
            "EVM Trace Gas (Total):".bold(),
            report.total_evm_gas.to_string().green()
        );
    }

    if report.total_stylus_ink > 0 {
        out += &format!(
            "  {:<34} {}\n",
            "Stylus Ink (raw):".bold(),
            report.total_stylus_ink.to_string().yellow()
        );
        out += &format!(
            "  {:<34} {}\n",
            "  → Gas-equivalent (÷10,000):".dimmed(),
            format!("{:.2}", report.total_stylus_gas_equiv).yellow()
        );
    }

    if report.vm_boundary_count > 0 {
        out += &format!(
            "  {:<34} {}\n",
            "VM Boundaries (EVM ↔ WASM):".bold(),
            report.vm_boundary_count.to_string().magenta()
        );
    }

    out += &format!("{div}\n");
    out += &format!(
        "  {:<34} {}\n",
        "TOTAL UNIFIED COST:".bold().cyan(),
        format!("{:.2} gas", report.total_unified_cost)
            .cyan()
            .bold()
    );
    out += &format!("{div}\n");

    // EVM step count always shown
    out += &format!(
        "  {:<34} {}\n",
        "EVM Steps:".bold(),
        evm_count(report).to_string().green()
    );

    // Stylus section — only when HostIO steps exist
    let stylus = report.stylus_steps();
    if !stylus.is_empty() {
        // Aggregate ink cost by label
        let mut grouped: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
        for step in stylus.iter() {
            *grouped.entry(step.label.clone()).or_insert(0.0) += step.cost_equiv;
        }
        let mut aggregated: Vec<(String, f64)> = grouped.into_iter().collect();
        aggregated.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());

        let total_ink_gas: f64 = aggregated.iter().map(|(_, c)| c).sum();
        let unique_paths = aggregated.len();

        out += &format!(
            "  {:<34} {}\n",
            "Stylus HostIO Calls:".bold(),
            stylus.len().to_string().yellow()
        );
        out += &format!(
            "  {:<34} {}\n",
            "Unique HostIO Paths:".bold(),
            unique_paths.to_string().yellow()
        );

        if report.vm_boundary_count > 0 {
            out += &format!("  {}\n", "EVM→WASM Boundary Details:".bold());
            for (i, step) in report.boundary_steps().iter().take(5).enumerate() {
                out += &format!(
                    "    {}  {} at depth {}\n",
                    format!("[{}]", i + 1).cyan(),
                    step.label.bold(),
                    step.depth.to_string().dimmed()
                );
            }
            if report.vm_boundary_count > 5 {
                out += &format!(
                    "    … and {} more\n",
                    (report.vm_boundary_count - 5).to_string().dimmed()
                );
            }
        }

        out += &format!("{div}\n");

        // ── Colour-coded hot-path table ────────────────────────────────────
        out += &format!("  {}\n", "🔥 STYLUS HOT PATHS".bold());
        out += &format!("  {wide_div}\n");
        out += &format!(
            "  ┃ {:<42} ┃ {:>10} ┃ {:>14} ┃ {:>7}\n",
            "HostIO (Hottest First)", "GAS", "INK (raw)", "%"
        );
        out += &format!("  {wide_div}\n");
        for (label, cost_gas) in aggregated.iter().take(10) {
            let cost_ink = (cost_gas * 10_000.0) as u64;
            let pct = if total_ink_gas > 0.0 {
                cost_gas / total_ink_gas * 100.0
            } else {
                0.0
            };
            let color = hostio_category_color(label);
            let gas_str = format!("{:.0}", cost_gas);
            out += &format!(
                "{color}{:<42}{RESET} ┃ {gas_str:>10} ┃ {cost_ink:>14} ┃ {pct:>6.1}% ┃\n",
                label,
            );
        }
        out += &format!("  {wide_div}\n");

        // ── ASCII flamegraph ───────────────────────────────────────────────
        out += &format!("\n  {}\n", "📊 SIMPLIFIED FLAMEGRAPH".bold());
        out += "  root ██████████████████████████████████████████████████ 100%\n";
        for (label, cost_gas) in aggregated.iter().take(5) {
            let pct = if total_ink_gas > 0.0 {
                cost_gas / total_ink_gas * 100.0
            } else {
                0.0
            };
            let bar_width = (pct / 2.0) as usize;
            let bar = "".repeat(bar_width);
            let color = hostio_category_color(label);
            out += &format!(
                "  └─ {color}{:<20}{RESET} {color}{:<50}{RESET} {:>5.1}%\n",
                label, bar, pct
            );
        }
        if unique_paths > 10 {
            out += &format!("\n   ({} of {} unique paths shown)\n", 10, unique_paths);
        }

        out += &format!("{div}\n");
    }

    out += &format!("  tx  {}\n", report.tx_hash.dimmed());
    out
}

fn print_aave_report(
    aave: &atupa_aave::LiquidationReport,
    nitro: &StitchedReport,
    top_selector: Option<&str>,
) {
    let div = "".repeat(56).dimmed().to_string();
    println!("{}", "  AAVE v3 PROTOCOL AUDIT".bold().underline());
    println!("{div}");

    // Show the actual top-level function called, resolved from calldata
    if let Some(sel) = top_selector {
        let fn_name = atupa_aave::AaveV3Adapter::resolve_selector_label(sel)
            .unwrap_or_else(|| format!("unknown ({})", sel));
        println!(
            "  {:<34} {}",
            "Top-Level Call:".bold(),
            fn_name.yellow().bold()
        );
    }

    let rows: &[(&str, String)] = &[
        ("Total Gas (Aave frame):", aave.total_gas.to_string()),
        ("Liquidation Gas:", aave.liquidation_gas.to_string()),
        ("Storage Reads (SLOAD):", aave.storage_reads.to_string()),
        ("Storage Writes (SSTORE):", aave.storage_writes.to_string()),
        ("External Calls:", aave.external_calls.to_string()),
        ("Oracle Calls:", aave.oracle_calls.to_string()),
        (
            "Cross-VM Calls (Stylus):",
            nitro.vm_boundary_count.to_string(),
        ),
        ("Max Call Depth:", aave.max_depth.to_string()),
    ];
    for (label, val) in rows {
        println!("  {:<34} {}", label.bold(), val.cyan());
    }
    println!("{div}");

    if !aave.labeled_calls.is_empty() {
        println!("  {}", "Protocol Calls Detected:".bold());
        for call in aave.labeled_calls.iter().take(10) {
            println!(
                "    {} {} {}",
                format!("[depth={:>2}]", call.depth).dimmed(),
                call.label.yellow(),
                format!("({} gas)", call.gas_cost).dimmed()
            );
        }
        println!("{div}");
    }

    println!(
        "  {:<34} {}",
        "Reverted:".bold(),
        if aave.reverted {
            "YES".red().bold().to_string()
        } else {
            "NO".green().to_string()
        }
    );
    println!(
        "  {:<34} {:.4}",
        "Liquidation Efficiency:".bold(),
        aave.liquidation_efficiency
    );
    println!("{div}");
}

fn print_lido_report(
    lido: &atupa_lido::LidoReport,
    nitro: &StitchedReport,
    top_selector: Option<&str>,
) {
    let div = "".repeat(56).dimmed().to_string();
    println!("{}", "  LIDO stETH PROTOCOL AUDIT".bold().underline());
    println!("{div}");

    // Show the actual top-level function called, resolved from calldata
    if let Some(sel) = top_selector {
        let fn_name = atupa_lido::LidoAdapter::resolve_selector_label(sel)
            .unwrap_or_else(|| format!("unknown fn ({})", sel));
        println!(
            "  {:<34} {}",
            "Top-Level Call:".bold(),
            fn_name.yellow().bold()
        );
    }

    let rows: &[(&str, String)] = &[
        ("Total Gas (Lido frame):", lido.total_gas.to_string()),
        ("Storage Reads (SLOAD):", lido.storage_reads.to_string()),
        ("Storage Writes (SSTORE):", lido.storage_writes.to_string()),
        ("External Calls:", lido.external_calls.to_string()),
        ("Shares Transfers:", lido.shares_transfers.to_string()),
        ("Oracle Reports:", lido.oracle_reports.to_string()),
        ("Withdrawal Requests:", lido.withdrawal_requests.to_string()),
        ("Withdrawal Claims:", lido.withdrawal_claims.to_string()),
        ("Wrapped Ops (wstETH):", lido.wrapped_ops.to_string()),
        (
            "Cross-VM Calls (Stylus):",
            nitro.vm_boundary_count.to_string(),
        ),
        ("Max Call Depth:", lido.max_depth.to_string()),
    ];
    for (label, val) in rows {
        println!("  {:<34} {}", label.bold(), val.cyan());
    }
    println!("{div}");

    if !lido.labeled_calls.is_empty() {
        println!("  {}", "Protocol Calls Detected:".bold());
        for call in lido.labeled_calls.iter().take(10) {
            println!(
                "    {} {} {}",
                format!("[depth={:>2}]", call.depth).dimmed(),
                call.label.yellow(),
                format!("({} gas)", call.gas_cost).dimmed()
            );
        }
        if lido.labeled_calls.len() > 10 {
            println!(
                "    ... and {} more",
                (lido.labeled_calls.len() - 10).to_string().dimmed()
            );
        }
        println!("{div}");
    }

    println!(
        "  {:<34} {}",
        "Reverted:".bold(),
        if lido.reverted {
            "YES".red().bold().to_string()
        } else {
            "NO".green().to_string()
        }
    );
    println!("{div}");
}

// ─── Shared Utilities ─────────────────────────────────────────────────────────

/// Normalise a transaction hash to lowercase 0x-prefixed form.
fn normalise_hash(tx: &str) -> String {
    let t = tx.trim();
    if t.to_lowercase().starts_with("0x") {
        t.to_lowercase()
    } else {
        format!("0x{}", t.to_lowercase())
    }
}

fn evm_count(r: &StitchedReport) -> usize {
    r.steps.iter().filter(|s| s.vm == VmKind::Evm).count()
}

/// Bridge `RawStructLog` (atupa-rpc) → `TraceStep` (atupa-core) for adapters
/// that still operate on the lower-level type.
fn bridge_raw_to_trace_step(raw: &RawStructLog) -> TraceStep {
    TraceStep {
        pc: raw.pc,
        op: raw.op.clone(),
        gas: raw.gas,
        gas_cost: raw.gas_cost,
        depth: raw.depth,
        stack: raw.stack.clone(),
        memory: raw.memory.clone(),
        error: raw.error.clone(),
        reverted: raw.error.is_some(),
        vm_kind: atupa_core::VmKind::Evm,
    }
}

fn spinner(msg: &str) -> ProgressBar {
    let pb = ProgressBar::new_spinner();
    pb.set_style(
        ProgressStyle::with_template("{spinner:.cyan} {msg}")
            .unwrap()
            .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
    );
    pb.enable_steady_tick(Duration::from_millis(80));
    pb.set_message(msg.to_string());
    pb
}

fn get_network_name(chain_id: u64) -> String {
    match chain_id {
        1 => "Ethereum Mainnet".to_string(),
        11155111 => "Sepolia Testnet".to_string(),
        17000 => "Holesky Testnet".to_string(),
        42161 => "Arbitrum One".to_string(),
        42170 => "Arbitrum Nova".to_string(),
        421614 => "Arbitrum Sepolia".to_string(),
        8453 => "Base Mainnet".to_string(),
        84532 => "Base Sepolia".to_string(),
        10 => "Optimism".to_string(),
        11155420 => "Optimism Sepolia".to_string(),
        137 => "Polygon POS".to_string(),
        1337 | 31337 => "Local Devnet".to_string(),
        412346 => "Nitro Local Devnet".to_string(),
        0 => "Unknown Network".to_string(),
        id => format!("Chain ID: {}", id),
    }
}

fn resolve_artifact_path(path: Option<String>, category: &str, tx_hash: &str, ext: &str) -> String {
    let filename = path.unwrap_or_else(|| {
        let short = tx_hash
            .trim_start_matches("0x")
            .get(..10)
            .unwrap_or(tx_hash);
        match ext {
            "json" => format!("report_{short}.json"),
            "svg" => format!("profile_{short}.svg"),
            _ => format!("artifact_{short}.{ext}"),
        }
    });

    let pb = std::path::PathBuf::from(&filename);
    // If it's a simple filename (no parent directory), move it to artifacts/<category>/
    if pb
        .parent()
        .map(|p| p.as_os_str().is_empty())
        .unwrap_or(true)
    {
        let dir = format!("artifacts/{}", category);
        let _ = std::fs::create_dir_all(&dir);
        format!("{}/{}", dir, filename)
    } else {
        filename
    }
}