stygian-browser 0.13.5

Anti-detection browser automation library for Rust with CDP stealth features
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Opinionated acquisition runner with deterministic escalation.
//!
//! The runner executes a mode-specific strategy ladder and returns a terminal
//! [`AcquisitionResult`] for every request, including setup-failure and timeout
//! paths.

use std::sync::Arc;
use std::time::{Duration, Instant};

#[cfg(feature = "browserbase")]
use chromiumoxide::Browser;
#[cfg(feature = "browserbase")]
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "browserbase")]
use tokio::time::timeout;

use crate::BrowserPool;
use crate::error::BrowserError;
use crate::page::WaitUntil;

/// Opinionated acquisition mode for the escalation ladder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AcquisitionMode {
    /// Prioritize lowest-latency paths.
    Fast,
    /// Favor reliability with broader escalation.
    Resilient,
    /// Start from stronger anti-bot paths.
    Hostile,
    /// Enter from a policy-guided start point.
    Investigate,
}

/// Strategy stage attempted by the acquisition runner.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StrategyUsed {
    /// Plain HTTP fetch.
    DirectHttp,
    /// HTTP fetch using a TLS-profiled client.
    TlsProfiledHttp,
    /// Browser session with opinionated light-stealth defaults.
    BrowserLightStealth,
    /// Browser session scoped to a sticky context id.
    StickyProxyBrowserSession,
    /// Managed remote browser session routed through Browserbase.
    #[cfg(feature = "browserbase")]
    BrowserbaseManagedSession,
    /// Policy-guided entry marker for investigation mode.
    InvestigateEntry,
}

/// One acquisition request.
#[derive(Debug, Clone)]
pub struct AcquisitionRequest {
    /// Target URL.
    pub url: String,
    /// Acquisition mode.
    pub mode: AcquisitionMode,
    /// Optional selector that must be present for browser-stage success.
    pub wait_for_selector: Option<String>,
    /// Optional JavaScript extraction expression evaluated in browser stages.
    pub extraction_js: Option<String>,
    /// Hard wall-clock timeout for the whole acquisition attempt.
    pub total_timeout: Duration,
    /// Per-navigation timeout for browser stages.
    pub navigation_timeout: Duration,
    /// Per-request timeout for HTTP stages.
    pub request_timeout: Duration,
    /// Maximum HTML bytes captured into `html_excerpt`.
    pub html_excerpt_bytes: usize,
    /// Optional policy-guided stage that `Investigate` mode starts from.
    pub investigate_start: Option<StrategyUsed>,
    /// Opt into the optional Browserbase-managed stage when available.
    pub browserbase_enabled: bool,
}

impl Default for AcquisitionRequest {
    fn default() -> Self {
        Self {
            url: String::new(),
            mode: AcquisitionMode::Resilient,
            wait_for_selector: None,
            extraction_js: None,
            total_timeout: Duration::from_secs(45),
            navigation_timeout: Duration::from_secs(30),
            request_timeout: Duration::from_secs(15),
            html_excerpt_bytes: 4_096,
            investigate_start: None,
            browserbase_enabled: false,
        }
    }
}

/// Failure class recorded per strategy stage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StageFailureKind {
    /// Stage initialization/setup failed.
    Setup,
    /// Stage hit a timeout.
    Timeout,
    /// Stage reached a known anti-bot block class.
    Blocked,
    /// Transport/runtime failure.
    Transport,
    /// Extraction/validation failure.
    Extraction,
}

/// Captured failure record for one stage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StageFailure {
    /// Stage where the failure happened.
    pub strategy: StrategyUsed,
    /// Coarse failure kind.
    pub kind: StageFailureKind,
    /// Compact diagnostic message.
    pub message: String,
}

/// Terminal acquisition result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcquisitionResult {
    /// `true` when any stage satisfied success criteria.
    pub success: bool,
    /// Stage that produced the terminal success, if any.
    pub strategy_used: Option<StrategyUsed>,
    /// Ordered stage attempts.
    pub attempted: Vec<StrategyUsed>,
    /// Final URL observed from the successful stage.
    pub final_url: Option<String>,
    /// HTTP status code observed from the successful stage.
    pub status_code: Option<u16>,
    /// Best-effort HTML excerpt from the successful stage.
    pub html_excerpt: Option<String>,
    /// Optional extraction payload.
    pub extracted: Option<Value>,
    /// Failure bundle collected across stages.
    pub failures: Vec<StageFailure>,
    /// `true` when the wall-clock timeout fired before completion.
    pub timed_out: bool,
}

impl AcquisitionResult {
    const fn empty() -> Self {
        Self {
            success: false,
            strategy_used: None,
            attempted: Vec::new(),
            final_url: None,
            status_code: None,
            html_excerpt: None,
            extracted: None,
            failures: Vec::new(),
            timed_out: false,
        }
    }
}

#[derive(Debug, Clone)]
struct StageSuccess {
    final_url: Option<String>,
    status_code: Option<u16>,
    html_excerpt: Option<String>,
    extracted: Option<Value>,
}

#[derive(Debug, Clone)]
enum StageOutcome {
    Marker,
    Success(StageSuccess),
    Failure(StageFailure),
}

/// Runner facade for opinionated acquisition.
#[derive(Clone)]
pub struct AcquisitionRunner {
    pool: Arc<BrowserPool>,
}

impl AcquisitionRunner {
    /// Create a new acquisition runner.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{AcquisitionRunner, BrowserConfig, BrowserPool};
    ///
    /// # async fn run() -> stygian_browser::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let _runner = AcquisitionRunner::new(pool);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn new(pool: Arc<BrowserPool>) -> Self {
        Self { pool }
    }

    /// Return the deterministic stage ladder for a mode.
    ///
    /// Investigation mode starts at `investigate_start` when provided.
    #[must_use]
    pub fn strategy_ladder(
        mode: AcquisitionMode,
        investigate_start: Option<StrategyUsed>,
    ) -> Vec<StrategyUsed> {
        let mut stages = match mode {
            AcquisitionMode::Fast => vec![
                StrategyUsed::DirectHttp,
                StrategyUsed::TlsProfiledHttp,
                StrategyUsed::BrowserLightStealth,
            ],
            AcquisitionMode::Resilient => vec![
                StrategyUsed::DirectHttp,
                StrategyUsed::TlsProfiledHttp,
                StrategyUsed::BrowserLightStealth,
                StrategyUsed::StickyProxyBrowserSession,
            ],
            AcquisitionMode::Hostile => vec![
                StrategyUsed::BrowserLightStealth,
                StrategyUsed::StickyProxyBrowserSession,
                StrategyUsed::TlsProfiledHttp,
                StrategyUsed::DirectHttp,
            ],
            AcquisitionMode::Investigate => {
                let start = investigate_start.unwrap_or(StrategyUsed::BrowserLightStealth);
                vec![
                    StrategyUsed::InvestigateEntry,
                    start,
                    StrategyUsed::StickyProxyBrowserSession,
                    StrategyUsed::TlsProfiledHttp,
                ]
            }
        };

        dedupe_preserve_order(&mut stages);
        stages
    }

    /// Execute the acquisition ladder and return a terminal result.
    ///
    /// This method never panics and always returns an [`AcquisitionResult`],
    /// including timeout and setup-failure paths.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use stygian_browser::{AcquisitionMode, AcquisitionRequest, AcquisitionRunner, BrowserConfig, BrowserPool};
    ///
    /// # async fn run() -> stygian_browser::Result<()> {
    /// let pool = BrowserPool::new(BrowserConfig::default()).await?;
    /// let runner = AcquisitionRunner::new(pool);
    /// let request = AcquisitionRequest {
    ///     url: "https://example.com".to_string(),
    ///     mode: AcquisitionMode::Resilient,
    ///     ..AcquisitionRequest::default()
    /// };
    /// let _result = runner.run(request).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run(&self, request: AcquisitionRequest) -> AcquisitionResult {
        let timeout = request.total_timeout;
        let timeout_strategy = Self::strategy_ladder(request.mode, request.investigate_start)
            .into_iter()
            .find(|strategy| *strategy != StrategyUsed::InvestigateEntry)
            .unwrap_or(StrategyUsed::DirectHttp);
        let mut result = tokio::time::timeout(timeout, self.run_inner(&request))
            .await
            .unwrap_or_else(|_| {
                let mut timed_out = AcquisitionResult::empty();
                timed_out.timed_out = true;
                timed_out.failures.push(StageFailure {
                    strategy: timeout_strategy,
                    kind: StageFailureKind::Timeout,
                    message: format!("acquisition timed out after {}ms", timeout.as_millis()),
                });
                timed_out
            });

        if !result.success {
            // Guarantee deterministic terminal output for all unsuccessful runs.
            if result.failures.is_empty() {
                result.failures.push(StageFailure {
                    strategy: timeout_strategy,
                    kind: StageFailureKind::Transport,
                    message: "acquisition ended without stage output".to_string(),
                });
            }
        }

        result
    }

    async fn run_inner(&self, request: &AcquisitionRequest) -> AcquisitionResult {
        let mut result = AcquisitionResult::empty();

        #[cfg(feature = "browserbase")]
        let mut ladder = Self::strategy_ladder(request.mode, request.investigate_start);

        #[cfg(not(feature = "browserbase"))]
        let ladder = Self::strategy_ladder(request.mode, request.investigate_start);

        #[cfg(feature = "browserbase")]
        {
            maybe_insert_browserbase_stage(&mut ladder, request.browserbase_enabled);
        }
        let started = Instant::now();

        for strategy in ladder {
            if started.elapsed() >= request.total_timeout {
                result.timed_out = true;
                result.failures.push(StageFailure {
                    strategy,
                    kind: StageFailureKind::Timeout,
                    message: "wall-clock timeout reached before stage execution".to_string(),
                });
                break;
            }

            result.attempted.push(strategy);
            match self.execute_stage(strategy, request).await {
                StageOutcome::Marker => {}
                StageOutcome::Success(success) => {
                    result.success = true;
                    result.strategy_used = Some(strategy);
                    result.final_url = success.final_url;
                    result.status_code = success.status_code;
                    result.html_excerpt = success.html_excerpt;
                    result.extracted = success.extracted;
                    break;
                }
                StageOutcome::Failure(failure) => result.failures.push(failure),
            }
        }

        result
    }

    async fn execute_stage(
        &self,
        strategy: StrategyUsed,
        request: &AcquisitionRequest,
    ) -> StageOutcome {
        match strategy {
            StrategyUsed::DirectHttp => {
                #[cfg(feature = "tls-config")]
                {
                    self.run_http_stage(request, false).await
                }

                #[cfg(not(feature = "tls-config"))]
                {
                    self.run_http_stage(request, false)
                }
            }
            StrategyUsed::TlsProfiledHttp => {
                #[cfg(feature = "tls-config")]
                {
                    self.run_http_stage(request, true).await
                }

                #[cfg(not(feature = "tls-config"))]
                {
                    self.run_http_stage(request, true)
                }
            }
            StrategyUsed::BrowserLightStealth => self.run_browser_stage(request, false).await,
            StrategyUsed::StickyProxyBrowserSession => self.run_browser_stage(request, true).await,
            #[cfg(feature = "browserbase")]
            StrategyUsed::BrowserbaseManagedSession => Self::run_browserbase_stage(request).await,
            StrategyUsed::InvestigateEntry => StageOutcome::Marker,
        }
    }

    #[cfg(feature = "browserbase")]
    #[allow(clippy::too_many_lines)]
    async fn run_browserbase_stage(request: &AcquisitionRequest) -> StageOutcome {
        if !request.browserbase_enabled {
            return StageOutcome::Failure(StageFailure {
                strategy: StrategyUsed::BrowserbaseManagedSession,
                kind: StageFailureKind::Setup,
                message: "browserbase stage disabled for this request".to_string(),
            });
        }

        let api_key = match std::env::var("BROWSERBASE_API_KEY") {
            Ok(value) if !value.trim().is_empty() => value,
            _ => {
                return StageOutcome::Failure(StageFailure {
                    strategy: StrategyUsed::BrowserbaseManagedSession,
                    kind: StageFailureKind::Setup,
                    message: "browserbase requires BROWSERBASE_API_KEY".to_string(),
                });
            }
        };

        let project_id = match std::env::var("BROWSERBASE_PROJECT_ID") {
            Ok(value) if !value.trim().is_empty() => value,
            _ => {
                return StageOutcome::Failure(StageFailure {
                    strategy: StrategyUsed::BrowserbaseManagedSession,
                    kind: StageFailureKind::Setup,
                    message: "browserbase requires BROWSERBASE_PROJECT_ID".to_string(),
                });
            }
        };

        let session = match create_browserbase_session(request, &api_key, &project_id).await {
            Ok(session) => session,
            Err(err) => {
                return StageOutcome::Failure(StageFailure {
                    strategy: StrategyUsed::BrowserbaseManagedSession,
                    kind: classify_browser_error(&err),
                    message: err.to_string(),
                });
            }
        };

        let connect_timeout = request.request_timeout.min(request.total_timeout);
        let (mut browser, mut handler) = match timeout(
            connect_timeout,
            Browser::connect(session.connect_url.clone()),
        )
        .await
        {
            Ok(Ok(pair)) => pair,
            Ok(Err(err)) => {
                let _ = delete_browserbase_session(request, &api_key, &session.id).await;
                return StageOutcome::Failure(StageFailure {
                    strategy: StrategyUsed::BrowserbaseManagedSession,
                    kind: StageFailureKind::Transport,
                    message: format!("browserbase connect failed: {err}"),
                });
            }
            Err(_) => {
                let _ = delete_browserbase_session(request, &api_key, &session.id).await;
                return StageOutcome::Failure(StageFailure {
                    strategy: StrategyUsed::BrowserbaseManagedSession,
                    kind: StageFailureKind::Timeout,
                    message: format!(
                        "browserbase connect timed out after {}ms",
                        connect_timeout.as_millis()
                    ),
                });
            }
        };

        let handler_task = tokio::spawn(async move {
            while let Some(event) = handler.next().await {
                if let Err(error) = event {
                    tracing::warn!(%error, "browserbase handler error");
                    break;
                }
            }
        });

        let run_result =
            async {
                let raw_page = browser.new_page("about:blank").await.map_err(|err| {
                    BrowserError::CdpError {
                        operation: "Browser.newPage".to_string(),
                        message: err.to_string(),
                    }
                })?;

                let mut page = crate::page::PageHandle::new(raw_page, request.navigation_timeout);

                page.navigate(
                    &request.url,
                    WaitUntil::DomContentLoaded,
                    request.navigation_timeout,
                )
                .await?;

                if let Some(selector) = &request.wait_for_selector {
                    page.wait_for_selector(selector, request.navigation_timeout)
                        .await?;
                }

                let extracted = match request.extraction_js.as_deref() {
                    Some(script) => Some(page.eval::<Value>(script).await.map_err(|err| {
                        BrowserError::ScriptExecutionFailed {
                            script: script.to_string(),
                            reason: err.to_string(),
                        }
                    })?),
                    None => None,
                };

                let html = page.content().await?;
                let final_url = page.url().await.ok();
                let status_code = page.status_code().ok().flatten();

                Ok::<StageSuccess, BrowserError>(StageSuccess {
                    final_url,
                    status_code,
                    html_excerpt: Some(truncate_html(&html, request.html_excerpt_bytes)),
                    extracted,
                })
            }
            .await;

        let _ = timeout(Duration::from_secs(5), browser.close()).await;
        handler_task.abort();
        let _ = delete_browserbase_session(request, &api_key, &session.id).await;

        match run_result {
            Ok(success) => {
                if is_block_status(success.status_code) {
                    StageOutcome::Failure(StageFailure {
                        strategy: StrategyUsed::BrowserbaseManagedSession,
                        kind: StageFailureKind::Blocked,
                        message: format!(
                            "blocked status during browserbase stage: {:?}",
                            success.status_code
                        ),
                    })
                } else {
                    StageOutcome::Success(success)
                }
            }
            Err(err) => StageOutcome::Failure(StageFailure {
                strategy: StrategyUsed::BrowserbaseManagedSession,
                kind: classify_browser_error(&err),
                message: err.to_string(),
            }),
        }
    }

    async fn run_browser_stage(&self, request: &AcquisitionRequest, sticky: bool) -> StageOutcome {
        let strategy = if sticky {
            StrategyUsed::StickyProxyBrowserSession
        } else {
            StrategyUsed::BrowserLightStealth
        };

        let handle_result = if sticky {
            let context = host_hint(&request.url).unwrap_or_else(|| "default".to_string());
            self.pool.acquire_for(&context).await
        } else {
            self.pool.acquire().await
        };

        let handle = match handle_result {
            Ok(handle) => handle,
            Err(err) => {
                return StageOutcome::Failure(StageFailure {
                    strategy,
                    kind: StageFailureKind::Setup,
                    message: format!("browser acquire failed: {err}"),
                });
            }
        };

        let page_result = async {
            let browser = handle.browser().ok_or_else(|| {
                BrowserError::ConfigError("browser handle already released".to_string())
            })?;
            let mut page = browser.new_page().await?;
            page.navigate(
                &request.url,
                WaitUntil::DomContentLoaded,
                request.navigation_timeout,
            )
            .await?;

            if let Some(selector) = &request.wait_for_selector {
                page.wait_for_selector(selector, request.navigation_timeout)
                    .await?;
            }

            let extracted = match request.extraction_js.as_deref() {
                Some(script) => Some(page.eval::<Value>(script).await.map_err(|err| {
                    BrowserError::ScriptExecutionFailed {
                        script: script.to_string(),
                        reason: err.to_string(),
                    }
                })?),
                None => None,
            };

            let html = page.content().await?;
            let final_url = page.url().await.ok();
            let status_code = page.status_code().ok().flatten();
            let html_excerpt = truncate_html(&html, request.html_excerpt_bytes);

            drop(page);

            Ok::<StageSuccess, BrowserError>(StageSuccess {
                final_url,
                status_code,
                html_excerpt: Some(html_excerpt),
                extracted,
            })
        }
        .await;

        handle.release().await;

        match page_result {
            Ok(success) => {
                if is_block_status(success.status_code) {
                    StageOutcome::Failure(StageFailure {
                        strategy,
                        kind: StageFailureKind::Blocked,
                        message: format!(
                            "blocked status during browser stage: {:?}",
                            success.status_code
                        ),
                    })
                } else {
                    StageOutcome::Success(success)
                }
            }
            Err(err) => StageOutcome::Failure(StageFailure {
                strategy,
                kind: classify_browser_error(&err),
                message: err.to_string(),
            }),
        }
    }

    #[cfg(feature = "tls-config")]
    async fn run_http_stage(
        &self,
        request: &AcquisitionRequest,
        tls_profiled: bool,
    ) -> StageOutcome {
        if request.wait_for_selector.is_some() || request.extraction_js.is_some() {
            return StageOutcome::Failure(StageFailure {
                strategy: if tls_profiled {
                    StrategyUsed::TlsProfiledHttp
                } else {
                    StrategyUsed::DirectHttp
                },
                kind: StageFailureKind::Extraction,
                message: "HTTP stages cannot satisfy selector/extraction requirements".to_string(),
            });
        }

        self.run_http_stage_impl(request, tls_profiled).await
    }

    #[cfg(not(feature = "tls-config"))]
    fn run_http_stage(&self, request: &AcquisitionRequest, tls_profiled: bool) -> StageOutcome {
        if request.wait_for_selector.is_some() || request.extraction_js.is_some() {
            return StageOutcome::Failure(StageFailure {
                strategy: if tls_profiled {
                    StrategyUsed::TlsProfiledHttp
                } else {
                    StrategyUsed::DirectHttp
                },
                kind: StageFailureKind::Extraction,
                message: "HTTP stages cannot satisfy selector/extraction requirements".to_string(),
            });
        }

        self.run_http_stage_impl(request, tls_profiled)
    }

    #[cfg(feature = "tls-config")]
    async fn run_http_stage_impl(
        &self,
        request: &AcquisitionRequest,
        tls_profiled: bool,
    ) -> StageOutcome {
        use crate::tls::{CHROME_131, build_profiled_client_preset};

        let strategy = if tls_profiled {
            StrategyUsed::TlsProfiledHttp
        } else {
            StrategyUsed::DirectHttp
        };

        let client = if tls_profiled {
            match build_profiled_client_preset(&CHROME_131, None) {
                Ok(client) => client,
                Err(err) => {
                    return StageOutcome::Failure(StageFailure {
                        strategy,
                        kind: StageFailureKind::Setup,
                        message: format!("tls-profiled client setup failed: {err}"),
                    });
                }
            }
        } else {
            match reqwest::Client::builder()
                .timeout(request.request_timeout)
                .cookie_store(true)
                .build()
            {
                Ok(client) => client,
                Err(err) => {
                    return StageOutcome::Failure(StageFailure {
                        strategy,
                        kind: StageFailureKind::Setup,
                        message: format!("http client setup failed: {err}"),
                    });
                }
            }
        };

        let response = match client
            .get(&request.url)
            .timeout(request.request_timeout)
            .send()
            .await
        {
            Ok(response) => response,
            Err(err) => {
                return StageOutcome::Failure(StageFailure {
                    strategy,
                    kind: if err.is_timeout() {
                        StageFailureKind::Timeout
                    } else {
                        StageFailureKind::Transport
                    },
                    message: err.to_string(),
                });
            }
        };

        let status_code = Some(response.status().as_u16());
        let final_url = Some(response.url().to_string());
        let html = match response.text().await {
            Ok(text) => text,
            Err(err) => {
                return StageOutcome::Failure(StageFailure {
                    strategy,
                    kind: StageFailureKind::Transport,
                    message: format!("response body read failed: {err}"),
                });
            }
        };

        if is_block_status(status_code) {
            return StageOutcome::Failure(StageFailure {
                strategy,
                kind: StageFailureKind::Blocked,
                message: format!("blocked status from HTTP stage: {status_code:?}"),
            });
        }

        StageOutcome::Success(StageSuccess {
            final_url,
            status_code,
            html_excerpt: Some(truncate_html(&html, request.html_excerpt_bytes)),
            extracted: None,
        })
    }

    #[cfg(not(feature = "tls-config"))]
    #[expect(
        clippy::unused_self,
        reason = "signature must match the tls-config variant for uniform call sites"
    )]
    fn run_http_stage_impl(
        &self,
        _request: &AcquisitionRequest,
        tls_profiled: bool,
    ) -> StageOutcome {
        let strategy = if tls_profiled {
            StrategyUsed::TlsProfiledHttp
        } else {
            StrategyUsed::DirectHttp
        };
        StageOutcome::Failure(StageFailure {
            strategy,
            kind: StageFailureKind::Setup,
            message: "HTTP acquisition requires the `tls-config` feature".to_string(),
        })
    }
}

#[cfg(feature = "browserbase")]
#[derive(Debug, Clone)]
struct BrowserbaseSession {
    id: String,
    connect_url: String,
}

#[cfg(feature = "browserbase")]
async fn create_browserbase_session(
    request: &AcquisitionRequest,
    api_key: &str,
    project_id: &str,
) -> Result<BrowserbaseSession, BrowserError> {
    let client = reqwest::Client::builder()
        .timeout(request.request_timeout)
        .build()
        .map_err(|err| {
            BrowserError::ConfigError(format!("browserbase client setup failed: {err}"))
        })?;

    let create_url = format!("{}/sessions", browserbase_api_base());
    let response = client
        .post(create_url.clone())
        .bearer_auth(api_key)
        .header("x-bb-api-key", api_key)
        .json(&serde_json::json!({ "projectId": project_id }))
        .send()
        .await
        .map_err(|err| BrowserError::ConnectionError {
            url: create_url.clone(),
            reason: err.to_string(),
        })?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        return Err(BrowserError::ConnectionError {
            url: create_url,
            reason: format!("session create failed ({status}): {body}"),
        });
    }

    let payload: Value = response
        .json()
        .await
        .map_err(|err| BrowserError::ConnectionError {
            url: browserbase_api_base(),
            reason: format!("session create response parse failed: {err}"),
        })?;

    let connect_url = browserbase_connect_url(&payload).ok_or_else(|| {
        BrowserError::ConfigError("browserbase response missing connect URL".to_string())
    })?;
    let session_id = browserbase_session_id(&payload).ok_or_else(|| {
        BrowserError::ConfigError("browserbase response missing session id".to_string())
    })?;

    Ok(BrowserbaseSession {
        id: session_id,
        connect_url,
    })
}

#[cfg(feature = "browserbase")]
async fn delete_browserbase_session(
    request: &AcquisitionRequest,
    api_key: &str,
    session_id: &str,
) -> Result<(), BrowserError> {
    let client = reqwest::Client::builder()
        .timeout(request.request_timeout)
        .build()
        .map_err(|err| {
            BrowserError::ConfigError(format!("browserbase client setup failed: {err}"))
        })?;

    let delete_url = format!("{}/sessions/{session_id}", browserbase_api_base());
    let response = client
        .delete(delete_url.clone())
        .bearer_auth(api_key)
        .header("x-bb-api-key", api_key)
        .send()
        .await
        .map_err(|err| BrowserError::ConnectionError {
            url: delete_url.clone(),
            reason: err.to_string(),
        })?;

    if response.status().is_success() {
        Ok(())
    } else {
        Err(BrowserError::ConnectionError {
            url: delete_url,
            reason: format!("session delete failed with status {}", response.status()),
        })
    }
}

#[cfg(feature = "browserbase")]
fn browserbase_api_base() -> String {
    std::env::var("BROWSERBASE_API_BASE")
        .unwrap_or_else(|_| "https://api.browserbase.com/v1".to_string())
        .trim_end_matches('/')
        .to_string()
}

#[cfg(feature = "browserbase")]
fn browserbase_session_id(payload: &Value) -> Option<String> {
    payload
        .get("id")
        .or_else(|| payload.get("sessionId"))
        .or_else(|| payload.get("session_id"))
        .or_else(|| payload.get("data").and_then(|v| v.get("id")))
        .or_else(|| payload.get("data").and_then(|v| v.get("sessionId")))
        .or_else(|| payload.get("data").and_then(|v| v.get("session_id")))
        .and_then(Value::as_str)
        .map(ToString::to_string)
}

#[cfg(feature = "browserbase")]
fn browserbase_connect_url(payload: &Value) -> Option<String> {
    [
        "connectUrl",
        "connect_url",
        "wsUrl",
        "ws_url",
        "websocketUrl",
        "websocket_url",
        "browserWSEndpoint",
        "wsEndpoint",
        "ws_endpoint",
    ]
    .iter()
    .find_map(|key| payload.get(*key).and_then(Value::as_str))
    .or_else(|| {
        payload.get("data").and_then(|data| {
            [
                "connectUrl",
                "connect_url",
                "wsUrl",
                "ws_url",
                "websocketUrl",
                "websocket_url",
                "browserWSEndpoint",
                "wsEndpoint",
                "ws_endpoint",
            ]
            .iter()
            .find_map(|key| data.get(*key).and_then(Value::as_str))
        })
    })
    .map(ToString::to_string)
}

fn dedupe_preserve_order(stages: &mut Vec<StrategyUsed>) {
    let mut seen = Vec::new();
    stages.retain(|stage| {
        if seen.contains(stage) {
            false
        } else {
            seen.push(*stage);
            true
        }
    });
}

#[cfg(feature = "browserbase")]
fn maybe_insert_browserbase_stage(stages: &mut Vec<StrategyUsed>, enabled: bool) {
    if !enabled || stages.contains(&StrategyUsed::BrowserbaseManagedSession) {
        return;
    }

    if let Some(pos) = stages
        .iter()
        .position(|stage| *stage == StrategyUsed::StickyProxyBrowserSession)
    {
        stages.insert(pos, StrategyUsed::BrowserbaseManagedSession);
    } else {
        stages.push(StrategyUsed::BrowserbaseManagedSession);
    }
}

fn classify_browser_error(error: &BrowserError) -> StageFailureKind {
    match error {
        BrowserError::Timeout { .. } => StageFailureKind::Timeout,
        BrowserError::NavigationFailed { reason, .. } if reason.contains("selector") => {
            StageFailureKind::Blocked
        }
        BrowserError::ScriptExecutionFailed { .. } => StageFailureKind::Extraction,
        BrowserError::ConfigError(_) | BrowserError::PoolExhausted { .. } => {
            StageFailureKind::Setup
        }
        BrowserError::ProxyUnavailable { .. }
        | BrowserError::ConnectionError { .. }
        | BrowserError::CdpError { .. }
        | BrowserError::LaunchFailed { .. }
        | BrowserError::NavigationFailed { .. }
        | BrowserError::Io(_)
        | BrowserError::StaleNode { .. } => StageFailureKind::Transport,
        #[cfg(feature = "extract")]
        BrowserError::ExtractionFailed(_) => StageFailureKind::Extraction,
    }
}

const fn is_block_status(status: Option<u16>) -> bool {
    matches!(status, Some(401 | 403 | 407 | 429 | 503))
}

fn truncate_html(html: &str, max_bytes: usize) -> String {
    if html.len() <= max_bytes {
        return html.to_string();
    }

    let mut out = String::new();
    for ch in html.chars() {
        if out.len() + ch.len_utf8() > max_bytes {
            break;
        }
        out.push(ch);
    }
    out
}

fn host_hint(url: &str) -> Option<String> {
    let without_scheme = url.split_once("://")?.1;
    let authority = without_scheme.split('/').next()?;
    let host = authority.rsplit('@').next()?.split(':').next()?;
    if host.is_empty() {
        None
    } else {
        Some(host.to_ascii_lowercase())
    }
}

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

    #[test]
    fn ladder_is_deterministic_for_modes() {
        assert_eq!(
            AcquisitionRunner::strategy_ladder(AcquisitionMode::Fast, None),
            vec![
                StrategyUsed::DirectHttp,
                StrategyUsed::TlsProfiledHttp,
                StrategyUsed::BrowserLightStealth,
            ]
        );

        assert_eq!(
            AcquisitionRunner::strategy_ladder(
                AcquisitionMode::Investigate,
                Some(StrategyUsed::StickyProxyBrowserSession)
            ),
            vec![
                StrategyUsed::InvestigateEntry,
                StrategyUsed::StickyProxyBrowserSession,
                StrategyUsed::TlsProfiledHttp,
            ]
        );
    }

    #[test]
    fn block_statuses_are_classified() {
        assert!(is_block_status(Some(403)));
        assert!(is_block_status(Some(429)));
        assert!(!is_block_status(Some(200)));
        assert!(!is_block_status(None));
    }

    #[test]
    fn host_hint_extracts_authority() {
        assert_eq!(
            host_hint("https://user:pass@example.com:8443/path"),
            Some("example.com".to_string())
        );
    }

    #[test]
    fn truncate_html_respects_utf8_boundaries() {
        let src = "abc😀def";
        let out = truncate_html(src, 5);
        assert_eq!(out, "abc");
    }

    #[cfg(feature = "browserbase")]
    #[test]
    fn browserbase_connect_url_is_extracted_from_nested_data() {
        let payload = serde_json::json!({
            "data": {
                "connectUrl": "wss://connect.browserbase.example/devtools/browser/abc"
            }
        });

        assert_eq!(
            browserbase_connect_url(&payload),
            Some("wss://connect.browserbase.example/devtools/browser/abc".to_string())
        );
    }

    #[cfg(feature = "browserbase")]
    #[test]
    fn browserbase_stage_is_inserted_before_sticky_stage() {
        let mut ladder = vec![
            StrategyUsed::DirectHttp,
            StrategyUsed::StickyProxyBrowserSession,
            StrategyUsed::TlsProfiledHttp,
        ];

        maybe_insert_browserbase_stage(&mut ladder, true);

        assert_eq!(
            ladder,
            vec![
                StrategyUsed::DirectHttp,
                StrategyUsed::BrowserbaseManagedSession,
                StrategyUsed::StickyProxyBrowserSession,
                StrategyUsed::TlsProfiledHttp,
            ]
        );
    }
}