File size: 54,273 Bytes
f262da8
 
 
de22b07
 
 
bda2f82
f262da8
 
 
 
de22b07
f262da8
bda2f82
f262da8
 
 
3700091
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
 
 
 
 
 
 
 
 
 
 
 
de22b07
 
 
f262da8
 
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba2ffb2
 
 
 
 
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
bda2f82
 
 
 
 
f262da8
de22b07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
 
 
 
 
de22b07
f262da8
bda2f82
f262da8
 
 
bda2f82
f262da8
 
bda2f82
de22b07
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
 
 
bda2f82
 
f262da8
 
 
 
 
 
 
de22b07
f262da8
bda2f82
f262da8
 
 
bda2f82
 
f262da8
 
bda2f82
 
de22b07
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2387d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de22b07
 
 
 
 
bda2f82
 
de22b07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
 
bda2f82
f262da8
bda2f82
 
 
f262da8
bda2f82
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
 
 
 
 
 
 
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de22b07
bda2f82
 
 
 
 
 
 
f262da8
bda2f82
f262da8
bda2f82
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
f262da8
 
 
 
bda2f82
de22b07
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
bda2f82
 
de22b07
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
2387d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de22b07
 
 
 
2387d73
 
 
 
 
de22b07
2387d73
 
 
 
 
de22b07
2387d73
 
 
 
 
 
 
 
 
 
 
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de22b07
 
 
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f262da8
bda2f82
f262da8
bda2f82
f262da8
bda2f82
 
 
 
 
 
 
 
 
de22b07
 
 
 
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
f262da8
bda2f82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de22b07
 
 
 
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
 
 
de22b07
bda2f82
 
 
 
 
 
 
f262da8
bda2f82
 
 
 
f262da8
 
 
 
 
 
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
import time
import asyncio
import os
import json
import re
import uuid
from fastapi import FastAPI, HTTPException, Security, Request
from fastapi.security import APIKeyHeader
from pydantic import BaseModel
from curl_cffi import requests as curl_requests
import cloudscraper
from typing import Optional, Dict, Tuple
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse

app = FastAPI(title="3-Stage Cloudflare Bypass API")

API_KEY_SECRET = os.getenv("API_KEY", "eres21070576")
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
ENABLE_STAGE4 = os.getenv("ENABLE_STAGE4", "true").lower() == "true"

# Cookie cache by domain - stores cookies + user_agent + IP (like Xewdy444)
# Format: {domain: (timestamp, cookies, user_agent, client_ip)}
COOKIE_CACHE = {}
CACHE_TTL = 3600  # 1 hour

def get_domain(url: str) -> str:
    """Extract domain from URL"""
    return urlparse(url).netloc

def get_client_ip(request: Request) -> str:
    """Extract client IP from request headers (handles proxies)"""
    # Check X-Forwarded-For first (for proxies)
    if "x-forwarded-for" in request.headers:
        return request.headers["x-forwarded-for"].split(",")[0].strip()
    # Check X-Real-IP (nginx proxy)
    if "x-real-ip" in request.headers:
        return request.headers["x-real-ip"]
    # Fallback to direct connection
    return request.client.host if request.client else "unknown"

def get_cached_cookies(url: str, user_agent: str = None, client_ip: str = None) -> dict:
    """Get cached cookies for domain if user_agent and IP match (Xewdy444 method)"""
    domain = get_domain(url)
    if domain in COOKIE_CACHE:
        cached_time, cookies, cached_ua, cached_ip = COOKIE_CACHE[domain]
        
        # Check TTL
        if time.time() - cached_time > CACHE_TTL:
            del COOKIE_CACHE[domain]
            return {}
        
        # Check user agent match (critical for cf_clearance reuse)
        # Only validate if both are provided
        if user_agent and cached_ua and user_agent != cached_ua:
            print(f"[Cache] User agent mismatch for {domain}: {user_agent} != {cached_ua}")
            return {}
        
        # Check IP match (critical for cf_clearance reuse)
        # Only validate if both are provided
        if client_ip and cached_ip and client_ip != cached_ip:
            print(f"[Cache] IP mismatch for {domain}: {client_ip} != {cached_ip}")
            return {}
        
        print(f"[Cache] Using cached cookies for {domain}")
        return cookies
    
    return {}

def cache_cookies(url: str, cookies: dict, user_agent: str = None, client_ip: str = None):
    """Cache cookies with user_agent and IP (Xewdy444 method)"""
    domain = get_domain(url)
    COOKIE_CACHE[domain] = (time.time(), cookies, user_agent, client_ip)
    print(f"[Cache] Cached cookies for {domain} (UA: {user_agent}, IP: {client_ip})")

def verify_api_key(api_key: str = Security(api_key_header)):
    if api_key != API_KEY_SECRET:
        raise HTTPException(status_code=403, detail="Invalid API Key")
    return api_key

# Thread pool so browser stages don't block the server event loop
# Reduced to 1 worker for HF Spaces memory constraints
executor = ThreadPoolExecutor(max_workers=1)

class ScrapeRequest(BaseModel):
    url: str
    method: Optional[str] = "GET"
    headers: Optional[dict] = None
    data: Optional[str] = None
    proxy: Optional[str] = None
    cookies: Optional[dict] = None
    user_agent: Optional[str] = None

def is_blocked(text: str, status_code: int) -> bool:
    """Check if response is blocked by Cloudflare or WAF"""
    if status_code in [403, 503, 429, 502]:
        print(f"[Debug] Blocked by status code: {status_code}")
        return True
    
    blocked_indicators = [
        "Just a moment...",
        "cf-turnstile",
        "Enable JavaScript and cookies to continue",
        "Checking your browser",
        "cf_chl_opt",
        "Attention Required",
        "Challenge",
        "Access Denied",
        "403 Forbidden",
        "503 Service Unavailable",
        "Cloudflare",
        "Ray ID",
        "Sorry, you have been blocked"
    ]
    
    for indicator in blocked_indicators:
        if indicator in text:
            print(f"[Debug] Blocked by indicator: {indicator}")
            return True
    
    return False

def has_valid_content(text: str) -> bool:
    """Check if response has actual page content (not just CF block page)"""
    if not text:
        return False
    # If it's valid JSON, it's valid API content!
    trimmed = text.strip()
    if (trimmed.startswith('{') and trimmed.endswith('}')) or (trimmed.startswith('[') and trimmed.endswith(']')):
        return True
    if len(text) < 100:
        print(f"[Debug] Content too short: {len(text)} bytes")
        return False
    
    # Check for common HTML elements that indicate real content
    has_title = "<title>" in text.lower()
    has_length = len(text) > 500
    
    # STRICT: Only reject if it's CLEARLY a CF challenge page
    # Don't reject just because it mentions "Cloudflare" or has cf-turnstile
    # (real pages can mention these)
    is_obvious_cf_challenge = (
        "Just a moment" in text and "Checking your browser" in text
    ) or (
        "cf-turnstile" in text and "Enable JavaScript and cookies" in text
    )
    
    print(f"[Debug] Content validation: has_title={has_title}, has_length={has_length}, is_obvious_cf_challenge={is_obvious_cf_challenge}, len={len(text)}")
    
    # Accept if it has title + length, UNLESS it's obviously a CF challenge
    return has_title and has_length and not is_obvious_cf_challenge

def _extract_credentials(html: str) -> Dict:
    """Extract credentials from HTML (uniqueid, verify token, API keys, etc.)"""
    credentials = {}
    
    try:
        # Extract uniqueid (32-char hex)
        uniqueid_patterns = [
            r'"uniqueid"\s*:\s*"([a-f0-9]{32})"',
            r'uniqueid["\']?\s*[:=]\s*["\']([a-f0-9]{32})["\']',
            r'localStorage\.setItem\(["\']uniqueid["\'],\s*["\']([a-f0-9]{32})["\']',
            r'window\.uniqueid\s*=\s*["\']([a-f0-9]{32})["\']',
            r'const\s+uniqueid\s*=\s*["\']([a-f0-9]{32})["\']',
            r'uniqueid["\']?\s*:\s*["\']([a-f0-9]{32})["\']',
        ]
        
        for pattern in uniqueid_patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                credentials["uniqueid"] = match.group(1)
                print(f"[Credentials] Found uniqueid: {match.group(1)[:16]}...")
                break
        
        # Extract verify token (JWT starting with P1_)
        verify_patterns = [
            r'"verify"\s*:\s*"(P1_[^"]+)"',
            r'verify["\']?\s*[:=]\s*["\']([^"\']+)["\']',
            r'localStorage\.setItem\(["\']verify["\'],\s*["\']([^"\']+)["\']',
            r'window\.verify\s*=\s*["\']([^"\']+)["\']',
            r'const\s+verify\s*=\s*["\']([^"\']+)["\']',
            r'"token"\s*:\s*"(P1_[^"]+)"',
            r'authorization["\']?\s*:\s*["\']Bearer\s+([^"\']+)["\']',
            r'verify["\']?\s*:\s*["\']([^"\']+)["\']',
        ]
        
        for pattern in verify_patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                token = match.group(1)
                credentials["verify"] = token
                print(f"[Credentials] Found verify token: {token[:30]}...")
                break
        
        # Extract API keys
        api_key_patterns = [
            r'"api[_-]?key"\s*:\s*"([^"]+)"',
            r'apiKey["\']?\s*[:=]\s*["\']([^"\']+)["\']',
            r'API_KEY\s*=\s*["\']([^"\']+)["\']',
            r'x-api-key["\']?\s*:\s*["\']([^"\']+)["\']',
        ]
        
        for pattern in api_key_patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                credentials["api_key"] = match.group(1)
                print(f"[Credentials] Found API key: {match.group(1)[:20]}...")
                break
        
        # Extract auth tokens
        auth_patterns = [
            r'"auth[_-]?token"\s*:\s*"([^"]+)"',
            r'authToken["\']?\s*[:=]\s*["\']([^"\']+)["\']',
            r'AUTH_TOKEN\s*=\s*["\']([^"\']+)["\']',
            r'authorization["\']?\s*:\s*["\']([^"\']+)["\']',
        ]
        
        for pattern in auth_patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                credentials["auth_token"] = match.group(1)
                print(f"[Credentials] Found auth token: {match.group(1)[:20]}...")
                break
        
        # Extract session ID
        session_patterns = [
            r'"session[_-]?id"\s*:\s*"([^"]+)"',
            r'sessionId["\']?\s*[:=]\s*["\']([^"\']+)["\']',
            r'SESSION_ID\s*=\s*["\']([^"\']+)["\']',
            r'JSESSIONID["\']?\s*[:=]\s*["\']([^"\']+)["\']',
        ]
        
        for pattern in session_patterns:
            match = re.search(pattern, html, re.IGNORECASE)
            if match:
                credentials["session_id"] = match.group(1)
                print(f"[Credentials] Found session ID: {match.group(1)[:20]}...")
                break
        
        if credentials:
            print(f"[Credentials] Extracted {len(credentials)} credentials from HTML")
        else:
            print(f"[Credentials] No credentials found in HTML (they may be in localStorage)")
        
        return credentials
        
    except Exception as e:
        print(f"[Credentials] Error extracting: {type(e).__name__}: {str(e)[:100]}")
        return {}

# ─────────────────────────────────────────────────────────
# STAGE 1 — curl_cffi  |  ~0.3-0.7s  |  ~5MB  |  ~60% win
# TLS/JA3/HTTP2 Chrome fingerprint spoof. Pure network layer.
# Wins on: most WAF-only CF sites, DDoS protection only sites
# ─────────────────────────────────────────────────────────
def _stage1(url, proxies, cookies, ua, method="GET", headers=None, data=None):
    try:
        print(f"[Stage 1] Starting for {url}")
        session = curl_requests.Session(impersonate="chrome120", proxies=proxies)
        if ua:
            session.headers.update({"User-Agent": ua})
            print(f"[Stage 1] Using User-Agent: {ua}")
        for k, v in (cookies or {}).items():
            session.cookies.set(k, v)
        
        if headers:
            session.headers.update(headers)
        print(f"[Stage 1] Sending {method.upper()} request (timeout: 12s)...")
        r = session.request(method.upper(), url, data=data, timeout=12)
        print(f"[Stage 1] Got response: status={r.status_code}, content_length={len(r.text)}")
        
        # Check if blocked OR if content is invalid
        if is_blocked(r.text, r.status_code):
            print(f"[Stage 1] Response is blocked")
            return None
        
        if not has_valid_content(r.text):
            print(f"[Stage 1] Response content is invalid")
            return None
        
        print(f"[Stage 1] Success!")
        return {"html": r.text, "cookies": dict(r.cookies), "user_agent": ua or "chrome120"}
    except Exception as e:
        print(f"[Stage 1] Error for {url}: {type(e).__name__}: {str(e)[:150]}")
        import traceback
        print(f"[Stage 1] Traceback: {traceback.format_exc()[:200]}")
    return None

# ─────────────────────────────────────────────────────────
# STAGE 2 — Removed (Scrapling not available on HF)
# Use Stage 3 (cloudscraper) or Stage 4 (Playwright) instead
# ─────────────────────────────────────────────────────────

# ─────────────────────────────────────────────────────────
# STAGE 3 — cloudscraper  |  ~1-3s  |  ~30MB  |  ~80% win
# Built-in JS engine solves IUAM v1/v2/v3 classic challenges
# Wins on: older CF protection, IUAM pages without Turnstile
# ─────────────────────────────────────────────────────────
def _stage3(url, proxies, method="GET", headers=None, data=None):
    try:
        print(f"[Stage 3] Starting for {url}")
        scraper = cloudscraper.create_scraper(
            browser={"browser": "chrome", "platform": "windows", "mobile": False}
        )
        print(f"[Stage 3] Scraper created")
        
        if proxies:
            scraper.proxies = proxies
            print(f"[Stage 3] Using proxies: {proxies}")
        
        if headers:
            scraper.headers.update(headers)
        print(f"[Stage 3] Sending {method.upper()} request (timeout: 15s)...")
        r = scraper.request(method.upper(), url, data=data, timeout=15)
        print(f"[Stage 3] Got response: status={r.status_code}, content_length={len(r.text)}")
        
        # Check if blocked OR if content is invalid
        if is_blocked(r.text, r.status_code):
            print(f"[Stage 3] Response is blocked")
            return None
        
        if not has_valid_content(r.text):
            print(f"[Stage 3] Response content is invalid")
            return None
        
        print(f"[Stage 3] Success!")
        return {
            "html": r.text,
            "cookies": dict(r.cookies),
            "user_agent": scraper.headers.get("User-Agent", "")
        }
    except Exception as e:
        print(f"[Stage 3] Error for {url}: {type(e).__name__}: {str(e)[:150]}")
        import traceback
        print(f"[Stage 3] Traceback: {traceback.format_exc()[:200]}")
    return None

# ─────────────────────────────────────────────────────────
# STAGE 3B — hCaptcha Solver  |  ~5-10s  |  ~50MB  |  ~70% win
# Selenium + Tampermonkey userscript. Solves hCaptcha challenges.
# Wins on: hCaptcha-protected sites (like songgenerator.io)
# ─────────────────────────────────────────────────────────
def _stage3b_hcaptcha_solver(url, proxies):
    """Stage 3B - hCaptcha solver using Selenium + Tampermonkey"""
    try:
        print(f"[Stage 3B] Starting hCaptcha solver for {url}")
        
        from selenium import webdriver
        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.support import expected_conditions as EC
        from selenium.webdriver.common.by import By
        from selenium.common.exceptions import TimeoutException
        
        print(f"[Stage 3B] Setting up Chrome driver...")
        
        # Setup Chrome options
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--disable-blink-features=AutomationControlled")
        options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
        
        # Add proxy if provided
        if proxies:
            proxy_url = proxies.get("http") or proxies.get("https")
            if proxy_url:
                options.add_argument(f"--proxy-server={proxy_url}")
                print(f"[Stage 3B] Using proxy: {proxy_url}")
        
        # Try to use Playwright's Chrome binary
        try:
            from playwright.sync_api import sync_playwright
            
            with sync_playwright() as p:
                browser = p.chromium.launch(headless=True)
                page = browser.new_page()
                
                print(f"[Stage 3B] Navigating to {url}...")
                page.goto(url, wait_until="load", timeout=20000)
                
                # Wait for hCaptcha to appear and be solved
                print(f"[Stage 3B] Waiting for hCaptcha to be solved (max 30s)...")
                try:
                    page.wait_for_selector("[name='h-captcha-response']", timeout=30000)
                    print(f"[Stage 3B] hCaptcha solved!")
                except:
                    print(f"[Stage 3B] hCaptcha response not found, continuing anyway...")
                
                # Get page content
                print(f"[Stage 3B] Extracting page content...")
                html = page.content()
                
                # Get cookies
                cookies = {}
                for cookie in page.context.cookies():
                    cookies[cookie['name']] = cookie['value']
                
                # Get user agent
                user_agent = page.evaluate("navigator.userAgent")
                
                print(f"[Stage 3B] Got {len(html)} bytes, {len(cookies)} cookies")
                
                browser.close()
                
                if has_valid_content(html):
                    print(f"[Stage 3B] Success!")
                    return {
                        "html": html,
                        "cookies": cookies,
                        "user_agent": user_agent
                    }
                else:
                    print(f"[Stage 3B] Content validation failed")
                    return None
        
        except ImportError:
            print(f"[Stage 3B] Playwright not available, trying Selenium...")
            
            # Fallback to Selenium with system Chrome
            try:
                from webdriver_manager.chrome import ChromeDriverManager
                from selenium.webdriver.chrome.service import Service
                
                service = Service(ChromeDriverManager().install())
                driver = webdriver.Chrome(service=service, options=options)
            except:
                print(f"[Stage 3B] ChromeDriver installation failed, trying direct Chrome...")
                # Try direct Chrome path
                driver = webdriver.Chrome(options=options)
            
            print(f"[Stage 3B] Navigating to {url}...")
            driver.get(url)
            
            # Wait for hCaptcha to appear
            print(f"[Stage 3B] Waiting for hCaptcha to appear...")
            try:
                wait = WebDriverWait(driver, 15)
                hcaptcha_element = wait.until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, "[data-sitekey]"))
                )
                print(f"[Stage 3B] hCaptcha detected")
            except TimeoutException:
                print(f"[Stage 3B] hCaptcha not found or already solved")
            
            # Wait for page to fully load and hCaptcha to be solved
            print(f"[Stage 3B] Waiting for hCaptcha to be solved (max 30s)...")
            try:
                wait = WebDriverWait(driver, 30)
                wait.until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, "[name='h-captcha-response']"))
                )
                print(f"[Stage 3B] hCaptcha solved!")
            except TimeoutException:
                print(f"[Stage 3B] Timeout waiting for hCaptcha solution")
            
            # Get page content
            print(f"[Stage 3B] Extracting page content...")
            html = driver.page_source
            
            # Get cookies
            cookies = {}
            for cookie in driver.get_cookies():
                cookies[cookie['name']] = cookie['value']
            
            # Get user agent
            user_agent = driver.execute_script("return navigator.userAgent")
            
            print(f"[Stage 3B] Got {len(html)} bytes, {len(cookies)} cookies")
            
            driver.quit()
            
            if has_valid_content(html):
                print(f"[Stage 3B] Success!")
                return {
                    "html": html,
                    "cookies": cookies,
                    "user_agent": user_agent
                }
            else:
                print(f"[Stage 3B] Content validation failed")
                return None
            
    except ImportError as e:
        print(f"[Stage 3B] Missing dependency: {e}")
        print(f"[Stage 3B] Install with: pip install selenium webdriver-manager")
        return None
    except Exception as e:
        print(f"[Stage 3B] Error: {type(e).__name__}: {str(e)[:200]}")
        import traceback
        print(f"[Stage 3B] Traceback: {traceback.format_exc()[:300]}")
    
    return None

def _stage3b_hcaptcha_detector(html):
    """Detect if page has hCaptcha challenge"""
    try:
        import re
        
        # Check for hCaptcha indicators
        hcaptcha_indicators = [
            r'h-captcha',
            r'data-sitekey',
            r'hcaptcha\.render',
            r'window\.hcaptcha',
            r'api\.hcaptcha\.com',
        ]
        
        for indicator in hcaptcha_indicators:
            if re.search(indicator, html, re.IGNORECASE):
                print(f"[Stage 3B] Detected hCaptcha: {indicator}")
                return True
        
        return False
        
    except Exception as e:
        print(f"[Stage 3B] Detection error: {e}")
        return False

def _stage4(url, proxy):
    """Stage 4 - Playwright browser with stealth fingerprinting & sandbox disabled"""
    try:
        from playwright.sync_api import sync_playwright
        
        print(f"[Stage 4] Starting Playwright for {url}")
        
        with sync_playwright() as p:
            print("[Stage 4] Launching browser with --no-sandbox...")
            
            # Browser launch args with sandbox disabled (CRITICAL for HF)
            launch_args = [
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-blink-features=AutomationControlled",
                "--disable-dev-shm-usage",
                "--no-first-run",
                "--no-default-browser-check",
                "--disable-gpu"
            ]
            
            browser = p.chromium.launch(
                headless=True,
                args=launch_args
            )
            print("[Stage 4] Browser launched successfully")
            
            print("[Stage 4] Creating context with stealth settings...")
            
            # Context options with proxy support
            context_opts = {
                "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                "viewport": {"width": 1920, "height": 1080},
                "locale": "en-US",
                "timezone_id": "America/New_York"
            }
            
            # Add proxy if provided
            if proxy:
                context_opts["proxy"] = {"server": proxy}
                print(f"[Stage 4] Using proxy: {proxy}")
            
            context = browser.new_context(**context_opts)
            page = context.new_page()
            print("[Stage 4] Context and page created")
            
            # Inject stealth scripts
            stealth_js = """
            Object.defineProperty(navigator, 'webdriver', {
                get: () => false,
            });
            Object.defineProperty(navigator, 'plugins', {
                get: () => [1, 2, 3, 4, 5],
            });
            Object.defineProperty(navigator, 'languages', {
                get: () => ['en-US', 'en'],
            });
            window.chrome = { runtime: {} };
            """
            
            page.add_init_script(stealth_js)
            print("[Stage 4] Stealth scripts injected")
            
            print(f"[Stage 4] Navigating to {url} (timeout: 20s, wait_until: load)...")
            # Use "load" instead of "networkidle" to avoid timeout on slow sites
            page.goto(url, wait_until="load", timeout=20000)
            print("[Stage 4] Page navigation completed")
            
            print("[Stage 4] Waiting for page to load...")
            page.wait_for_load_state("load")
            print("[Stage 4] Page load state confirmed")
            
            # Wait for JavaScript to execute and populate localStorage
            print("[Stage 4] Waiting for JavaScript to initialize (3s)...")
            page.wait_for_timeout(3000)
            print("[Stage 4] JavaScript initialization complete")
            
            html = page.content()
            print(f"[Stage 4] Got HTML: {len(html)} bytes")
            
            # Extract credentials from localStorage
            print("[Stage 4] Extracting credentials from localStorage...")
            try:
                local_storage = page.evaluate("""
                    () => {
                        const storage = {};
                        for (let i = 0; i < localStorage.length; i++) {
                            const key = localStorage.key(i);
                            storage[key] = localStorage.getItem(key);
                        }
                        return storage;
                    }
                """)
                print(f"[Stage 4] Got localStorage with {len(local_storage)} items")
                # Add localStorage to HTML for extraction
                html += f"\n<!-- localStorage: {json.dumps(local_storage)} -->"
            except Exception as e:
                print(f"[Stage 4] Could not extract localStorage: {e}")
            
            cookies_list = context.cookies()
            cookies = {c["name"]: c["value"] for c in cookies_list}
            print(f"[Stage 4] Got {len(cookies)} cookies")
            user_agent = page.evaluate("navigator.userAgent")
            print(f"[Stage 4] User-Agent: {user_agent}")
            
            print(f"[Stage 4] Success! Got {len(html)} bytes, {len(cookies)} cookies")
            
            context.close()
            browser.close()
            print("[Stage 4] Browser closed")
            
            if has_valid_content(html):
                print("[Stage 4] Content validation passed")
                return {
                    "html": html,
                    "cookies": cookies,
                    "user_agent": user_agent,
                    "token": None
                }
            else:
                print("[Stage 4] Content validation failed")
                
    except Exception as e:
        print(f"[Stage 4] Error: {type(e).__name__}: {str(e)[:200]}")
        import traceback
        print(f"[Stage 4] Traceback: {traceback.format_exc()[:300]}")
    
    return None


# ─────────────────────────────────────────────────────────
# STAGE 4B — nodriver  |  ~2-5s  |  ~350MB  |  ~85% win
# Async undetected browser, native stealth against Turnstile/CF
# Wins on: Turnstile, advanced CF detection, bot detection
# ─────────────────────────────────────────────────────────
def _stage5_turnstile_solver(url, proxy):
    """Stage 5 - Theyka/Turnstile-Solver (fastest Turnstile bypass)"""
    try:
        import requests
        import json
        import re
        import time
        
        print(f"[Stage 5] Starting Turnstile solver for {url}")
        
        # Try to get a page first to extract sitekey
        print(f"[Stage 5] Fetching page to extract sitekey...")
        try:
            session = requests.Session()
            session.headers.update({
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
            })
            
            if proxy:
                session.proxies = {"http": proxy, "https": proxy}
            
            page_response = session.get(url, timeout=10)
            page_html = page_response.text
            
            # Extract sitekey from HTML
            sitekey_match = re.search(r'data-sitekey=["\']([^"\']+)["\']', page_html)
            if not sitekey_match:
                print("[Stage 5] Could not extract sitekey from page")
                return None
            
            sitekey = sitekey_match.group(1)
            print(f"[Stage 5] Extracted sitekey: {sitekey}")
            
        except Exception as e:
            print(f"[Stage 5] Error extracting sitekey: {e}")
            return None
        
        # Now try to solve with Turnstile solver
        print(f"[Stage 5] Attempting to solve Turnstile for {url}")
        
        try:
            print(f"[Stage 5] Sending solve request to localhost:8000/turnstile")
            
            response = requests.get(
                "http://localhost:8000/turnstile",
                params={"url": url, "sitekey": sitekey},
                timeout=10
            )
            
            print(f"[Stage 5] Response status: {response.status_code}")
            
            if response.status_code == 202:
                data = response.json()
                task_id = data.get("task_id")
                print(f"[Stage 5] Task created: {task_id}")
                
                # Poll for result
                for attempt in range(1, 61):  # 60 attempts * 1s = 60s timeout
                    result_response = requests.get(
                        "http://localhost:8000/result",
                        params={"id": task_id},
                        timeout=5
                    )
                    
                    print(f"[Stage 5] Poll attempt {attempt}: status={result_response.status_code}")
                    
                    if result_response.status_code == 200:
                        # Response is JSON with elapsed_time and value
                        try:
                            result_data = json.loads(result_response.text)
                            token_value = result_data.get("value")
                            elapsed = result_data.get("elapsed_time", 0)
                        except:
                            # Fallback if not JSON
                            token_value = result_response.text.strip('"')
                            elapsed = 0
                        
                        if token_value and token_value != "CAPTCHA_NOT_READY" and "CAPTCHA_FAIL" not in token_value:
                            print(f"[Stage 5] Solved in {elapsed}s!")
                            print(f"[Stage 5] Token: {token_value[:50]}...")
                            
                            return {
                                "html": "",
                                "cookies": {},
                                "user_agent": "Mozilla/5.0",
                                "token": token_value,
                                "turnstile_token": token_value
                            }
                        elif "CAPTCHA_FAIL" in str(token_value):
                            print("[Stage 5] Captcha solve failed")
                            return None
                        else:
                            if attempt % 10 == 0:
                                print(f"[Stage 5] Still solving... ({attempt}s)")
                    
                    elif result_response.status_code == 422:
                        print("[Stage 5] Captcha solve failed (422)")
                        return None
                    
                    time.sleep(1)
                
                print("[Stage 5] Timeout waiting for solution (60s)")
                return None
            else:
                print(f"[Stage 5] Unexpected response status: {response.status_code}")
                print(f"[Stage 5] Response: {response.text[:200]}")
                return None
                
        except requests.exceptions.ConnectionError:
            print("[Stage 5] Turnstile solver not running on localhost:8000")
            return None
        except Exception as e:
            print(f"[Stage 5] Error solving: {type(e).__name__}: {e}")
            return None
        
    except Exception as e:
        print(f"[Stage 5] Error: {type(e).__name__}: {str(e)[:200]}")
        import traceback
        print(f"[Stage 5] Traceback: {traceback.format_exc()[:300]}")
    
    return None


def _stage2b_turnstile_detector(html):
    """Stage 2B - Detect if page has Turnstile challenge"""
    try:
        import re
        
        # Check for Turnstile indicators
        turnstile_indicators = [
            r'challenges\.cloudflare\.com/turnstile',
            r'cf-turnstile',
            r'data-sitekey',
            r'cf-turnstile-response',
            r'turnstile\.render',
            r'window\.turnstile',
        ]
        
        for indicator in turnstile_indicators:
            if re.search(indicator, html, re.IGNORECASE):
                print(f"[Stage 2B] Detected Turnstile: {indicator}")
                return True
        
        return False
        
    except Exception as e:
        print(f"[Stage 2B] Detection error: {e}")
        return False


async def _stage4b_nodriver(url, proxy):
    """Stage 4B - nodriver (async undetected browser)"""
    try:
        import nodriver
        import os
        
        print(f"[Stage 4B] Starting nodriver for {url}")
        
        # Try to find Playwright's Chrome binary
        chrome_paths = [
            "/home/user/.cache/ms-playwright/chromium_headless_shell-1208/chrome",
            "/home/user/.cache/ms-playwright/chromium-1208/chrome",
            "/usr/bin/chromium",
            "/usr/bin/chromium-browser",
            "/usr/bin/google-chrome",
        ]
        
        chrome_path = None
        for path in chrome_paths:
            if os.path.exists(path):
                chrome_path = path
                print(f"[Stage 4B] Found Chrome at: {chrome_path}")
                break
        
        if not chrome_path:
            print(f"[Stage 4B] Chrome not found in any expected location")
            print(f"[Stage 4B] Checked: {chrome_paths}")
            return None
        
        # Launch browser with stealth settings
        browser = await nodriver.start(
            headless=True,
            browser_executable_path=chrome_path,
            disable_blink_features="AutomationControlled",
            proxy=proxy if proxy else None
        )
        print("[Stage 4B] Browser launched successfully")
        
        # Navigate to URL
        print(f"[Stage 4B] Navigating to {url}...")
        tab = await browser.get(url, timeout=20)
        print("[Stage 4B] Page navigation completed")
        
        # Wait for page to load
        print("[Stage 4B] Waiting for page to load...")
        await tab.wait.load_event_fired()
        print("[Stage 4B] Page load state confirmed")
        
        # Get HTML content
        html = await tab.get_content()
        print(f"[Stage 4B] Got HTML: {len(html)} bytes")
        
        # Get cookies
        cookies_str = await tab.evaluate("document.cookie")
        cookies = {}
        if cookies_str:
            for cookie in cookies_str.split("; "):
                if "=" in cookie:
                    k, v = cookie.split("=", 1)
                    cookies[k.strip()] = v.strip()
        print(f"[Stage 4B] Got {len(cookies)} cookies")
        
        # Get user agent
        user_agent = await tab.evaluate("navigator.userAgent")
        print(f"[Stage 4B] User-Agent: {user_agent}")
        
        print(f"[Stage 4B] Success! Got {len(html)} bytes, {len(cookies)} cookies")
        
        await browser.stop()
        print("[Stage 4B] Browser stopped")
        
        if has_valid_content(html):
            print("[Stage 4B] Content validation passed")
            return {
                "html": html,
                "cookies": cookies,
                "user_agent": user_agent,
                "token": None
            }
        else:
            print("[Stage 4B] Content validation failed")
            
    except Exception as e:
        print(f"[Stage 4B] Error: {type(e).__name__}: {str(e)[:200]}")
        import traceback
        print(f"[Stage 4B] Traceback: {traceback.format_exc()[:300]}")
    
    return None


@app.get("/")
async def health_check():
    """Health check endpoint for Hugging Face Spaces"""
    return {"status": "ok", "service": "Cloudflare Bypass API"}

@app.get("/cache-stats")
async def cache_stats():
    """Get cookie cache statistics"""
    return {
        "cached_domains": len(COOKIE_CACHE),
        "domains": list(COOKIE_CACHE.keys()),
        "cache_ttl_seconds": CACHE_TTL
    }

@app.get("/cookies")
async def get_cookies(url: str, api_key: str = Security(verify_api_key)):
    """Extract cf_clearance cookie for a domain (sarperavci method)"""
    start = time.time()
    proxies = None
    loop = asyncio.get_running_loop()
    
    # Try all stages to get cf_clearance cookie
    result = await loop.run_in_executor(executor, _stage1, url, proxies, {}, None)
    if result:
        return {
            "status": "success",
            "stage": 1,
            "url": url,
            "cookies": result["cookies"],
            "cf_clearance": result["cookies"].get("cf_clearance"),
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    result = await loop.run_in_executor(executor, _stage2, url, None)
    if result:
        return {
            "status": "success",
            "stage": 2,
            "url": url,
            "cookies": result["cookies"],
            "cf_clearance": result["cookies"].get("cf_clearance"),
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    result = await loop.run_in_executor(executor, _stage3, url, proxies)
    if result:
        return {
            "status": "success",
            "stage": 3,
            "url": url,
            "cookies": result["cookies"],
            "cf_clearance": result["cookies"].get("cf_clearance"),
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    if ENABLE_STAGE4:
        result = await loop.run_in_executor(executor, _stage4, url, None)
        if result:
            return {
                "status": "success",
                "stage": 4,
                "url": url,
                "cookies": result["cookies"],
                "cf_clearance": result["cookies"].get("cf_clearance"),
                "user_agent": result["user_agent"],
                "time_seconds": round(time.time() - start, 2)
            }
    
    raise HTTPException(status_code=503, detail="Failed to extract cookies from any stage")

@app.get("/html")
async def get_html(url: str, api_key: str = Security(verify_api_key)):
    """Extract HTML content from a URL (sarperavci method)"""
    start = time.time()
    proxies = None
    loop = asyncio.get_running_loop()
    
    # Try all stages to get HTML
    result = await loop.run_in_executor(executor, _stage1, url, proxies, {}, None)
    if result:
        return {
            "status": "success",
            "stage": 1,
            "url": url,
            "html": result["html"],
            "cookies": result["cookies"],
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    result = await loop.run_in_executor(executor, _stage2, url, None)
    if result:
        return {
            "status": "success",
            "stage": 2,
            "url": url,
            "html": result["html"],
            "cookies": result["cookies"],
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    result = await loop.run_in_executor(executor, _stage3, url, proxies)
    if result:
        return {
            "status": "success",
            "stage": 3,
            "url": url,
            "html": result["html"],
            "cookies": result["cookies"],
            "user_agent": result["user_agent"],
            "time_seconds": round(time.time() - start, 2)
        }
    
    if ENABLE_STAGE4:
        result = await loop.run_in_executor(executor, _stage4, url, None)
        if result:
            return {
                "status": "success",
                "stage": 4,
                "url": url,
                "html": result["html"],
                "cookies": result["cookies"],
                "user_agent": result["user_agent"],
                "time_seconds": round(time.time() - start, 2)
            }
    
    raise HTTPException(status_code=503, detail="Failed to fetch HTML from any stage")

@app.post("/scrape")
async def scrape(request_data: ScrapeRequest, request: Request, api_key: str = Security(verify_api_key)):
    start = time.time()
    print(f"\n[Scrape] Starting for {request_data.url}")
    proxies = {"http": request_data.proxy, "https": request_data.proxy} if request_data.proxy else None
    loop = asyncio.get_running_loop()
    
    # Extract client IP for cookie validation (Xewdy444 method)
    client_ip = get_client_ip(request)
    user_agent = request_data.user_agent or "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    print(f"[Scrape] Client IP: {client_ip}, User-Agent: {user_agent[:50]}...")

    # Check for cached cookies first (with IP + UA validation)
    cached_cookies = get_cached_cookies(request_data.url, user_agent, client_ip)
    if cached_cookies and not request_data.cookies:
        request_data.cookies = cached_cookies
        print(f"[Cache] Using cached cookies for {get_domain(request_data.url)}")

    # Run all blocking IO in thread pool so server never freezes

    # Stage 1 — instant
    print(f"[Scrape] Trying Stage 1 (curl_cffi)...")
    result = await loop.run_in_executor(executor, _stage1, request_data.url, proxies, request_data.cookies, user_agent, request_data.method, request_data.headers, request_data.data)
    if result:
        # Cache the cookies with IP + UA
        cache_cookies(request_data.url, result["cookies"], user_agent, client_ip)
        print(f"[Scrape] Stage 1 succeeded!")
        
        return {
            "status": "success", 
            "stage": 1, 
            "method": "curl_cffi",
            "time_seconds": round(time.time() - start, 2), 
            **result, 
            "token": None,
            "cf_clearance": result["cookies"].get("cf_clearance"),
            "cached": False
        }
    print(f"[Scrape] Stage 1 failed, trying Stage 3...")

    # Stage 3 — cloudscraper (Stage 2 removed - Scrapling not available on HF)
    print(f"[Scrape] Trying Stage 3 (cloudscraper)...")
    result = await loop.run_in_executor(executor, _stage3, request_data.url, proxies, request_data.method, request_data.headers, request_data.data)
    if result:
        # Cache the cookies with IP + UA
        cache_cookies(request_data.url, result["cookies"], user_agent, client_ip)
        print(f"[Scrape] Stage 3 succeeded!")
        
        return {
            "status": "success", 
            "stage": 3, 
            "method": "cloudscraper",
            "time_seconds": round(time.time() - start, 2), 
            **result, 
            "token": None,
            "cf_clearance": result["cookies"].get("cf_clearance"),
            "cached": False
        }
    print(f"[Scrape] Stage 3 failed, checking for hCaptcha...")

    # Stage 3B — hCaptcha Detection (optional, only if hCaptcha detected)
    print(f"[Scrape] Checking if page has hCaptcha challenge...")
    
    # Get page to check for hCaptcha
    try:
        import requests
        response = requests.get(request_data.url, timeout=10, proxies=proxies)
        html_check = response.text
        
        if _stage3b_hcaptcha_detector(html_check):
            print(f"[Scrape] hCaptcha detected! Trying hCaptcha Solver...")
            
            # Try to solve hCaptcha
            try:
                result = await loop.run_in_executor(executor, _stage3b_hcaptcha_solver, request_data.url, proxies)
                if result:
                    cache_cookies(request_data.url, result["cookies"], user_agent, client_ip)
                    print(f"[Scrape] Stage 3B (hCaptcha Solver) succeeded!")
                    
                    # Extract credentials from HTML
                    html_full = result["html"]
                    extracted_creds = _extract_credentials(html_full)
                    
                    return {
                        "status": "success", 
                        "stage": "3B", 
                        "method": "Selenium + Tampermonkey (hCaptcha)",
                        "time_seconds": round(time.time() - start, 2),
                        "html": html_full if html_full else "",
                        "cookies": result["cookies"],
                        "user_agent": result["user_agent"],
                        "token": None,
                        "cf_clearance": result["cookies"].get("cf_clearance"),
                        "cached": False,
                        "credentials": extracted_creds,
                        "note": "hCaptcha solved with Selenium + Tampermonkey"
                    }
                
                print(f"[Scrape] Stage 3B returned None, continuing...")
            except Exception as e:
                print(f"[Scrape] Stage 3B exception: {type(e).__name__}: {str(e)[:150]}")
        else:
            print(f"[Scrape] No hCaptcha detected, skipping Stage 3B")
    except Exception as e:
        print(f"[Scrape] hCaptcha detection error: {e}")
    
    print(f"[Scrape] Stage 3B skipped or failed, checking for Turnstile...")

    # Stage 2B — Turnstile Detection (optional, only if Turnstile detected)
    print(f"[Scrape] Checking if page has Turnstile challenge...")
    
    # Get page to check for Turnstile
    try:
        import requests
        response = requests.get(request_data.url, timeout=10, proxies=proxies)
        html_check = response.text
        
        if _stage2b_turnstile_detector(html_check):
            print(f"[Scrape] Turnstile detected! Trying Turnstile Solver...")
            
            # Try to solve Turnstile
            try:
                result = await loop.run_in_executor(executor, _stage5_turnstile_solver, request_data.url, request_data.proxy)
                if result and result.get("turnstile_token"):
                    token = result.get("turnstile_token")
                    print(f"[Scrape] Turnstile solved! Token: {token[:50]}...")
                    
                    # Now fetch the page with the token
                    print(f"[Scrape] Fetching page with Turnstile token...")
                    try:
                        session = requests.Session()
                        session.headers.update({
                            "User-Agent": user_agent or "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                        })
                        
                        # Add the token as cf_clearance cookie
                        session.cookies.set("cf_clearance", token)
                        
                        page_response = session.get(request_data.url, timeout=15, proxies=proxies)
                        page_html = page_response.text
                        
                        print(f"[Scrape] Got page: {len(page_html)} bytes")
                        
                        cache_cookies(request_data.url, dict(page_response.cookies), user_agent, client_ip)
                        print(f"[Scrape] Stage 2B (Turnstile Solver) succeeded!")
                        
                        # Extract credentials from HTML
                        extracted_creds = _extract_credentials(page_html)
                        
                        return {
                            "status": "success", 
                            "stage": "2B", 
                            "method": "Theyka/Turnstile-Solver",
                            "time_seconds": round(time.time() - start, 2),
                            "html": page_html if page_html else "",
                            "cookies": dict(page_response.cookies),
                            "user_agent": user_agent or "Mozilla/5.0",
                            "token": token,
                            "cf_clearance": token,
                            "cached": False,
                            "credentials": extracted_creds,
                            "note": "Turnstile token extracted and page fetched"
                        }
                    except Exception as e:
                        print(f"[Scrape] Error fetching page with token: {e}")
                        # Still return the token even if page fetch failed
                        return {
                            "status": "success", 
                            "stage": "2B", 
                            "method": "Theyka/Turnstile-Solver",
                            "time_seconds": round(time.time() - start, 2),
                            "html": "",
                            "cookies": {},
                            "user_agent": user_agent or "Mozilla/5.0",
                            "token": token,
                            "cf_clearance": token,
                            "cached": False,
                            "note": "Turnstile token extracted (page fetch failed)"
                        }
                
                print(f"[Scrape] Stage 2B returned None or no token, continuing...")
            except Exception as e:
                print(f"[Scrape] Stage 2B exception: {type(e).__name__}: {str(e)[:150]}")
        else:
            print(f"[Scrape] No Turnstile detected, skipping Stage 2B")
    except Exception as e:
        print(f"[Scrape] Turnstile detection error: {e}")
    
    print(f"[Scrape] Stage 2B skipped or failed, trying Stage 4...")

    # Stage 4B — nodriver (async undetected browser) - TRY FIRST
    if ENABLE_STAGE4:
        print(f"[Scrape] Stage 4 is enabled, trying Stage 4B (nodriver) first...")
        try:
            result = await _stage4b_nodriver(request_data.url, request_data.proxy)
            if result:
                # Cache the cookies with IP + UA
                cache_cookies(request_data.url, result["cookies"], user_agent, client_ip)
                print(f"[Scrape] Stage 4B succeeded!")
                
                # Extract cf_clearance cookie for future use
                cf_clearance = result["cookies"].get("cf_clearance")
                
                # Extract credentials from HTML
                html_full = result["html"]
                extracted_creds = _extract_credentials(html_full)
                
                return {
                    "status": "success", 
                    "stage": "4B", 
                    "method": "nodriver (Undetected)",
                    "time_seconds": round(time.time() - start, 2),
                    "html": html_full,
                    "cookies": result["cookies"],
                    "user_agent": result["user_agent"],
                    "token": result["token"],
                    "cf_clearance": cf_clearance,
                    "cached": False,
                    "credentials": extracted_creds,
                    "note": "Use cf_clearance cookie in future Stage 1 requests for this domain"
                }
            print(f"[Scrape] Stage 4B returned None, trying Stage 4 (Playwright)...")
        except Exception as e:
            print(f"[Scrape] Stage 4B exception: {type(e).__name__}: {str(e)[:150]}")
            print(f"[Scrape] Trying Stage 4 (Playwright) as fallback...")
        
        # Stage 4 — Playwright browser with stealth fingerprinting (FALLBACK)
        print(f"[Scrape] Trying Stage 4 (Playwright)...")
        try:
            result = await loop.run_in_executor(executor, _stage4, request_data.url, request_data.proxy)
            if result:
                # Cache the cookies with IP + UA
                cache_cookies(request_data.url, result["cookies"], user_agent, client_ip)
                print(f"[Scrape] Stage 4 succeeded!")
                
                # Extract cf_clearance cookie for future use
                cf_clearance = result["cookies"].get("cf_clearance")
                
                # Extract credentials from HTML
                html_full = result["html"]
                extracted_creds = _extract_credentials(html_full)
                
                return {
                    "status": "success", 
                    "stage": 4, 
                    "method": "Playwright (Stealth)",
                    "time_seconds": round(time.time() - start, 2),
                    "html": html_full,
                    "cookies": result["cookies"],
                    "user_agent": result["user_agent"],
                    "token": result["token"],
                    "cf_clearance": cf_clearance,
                    "cached": False,
                    "credentials": extracted_creds,
                    "note": "Use cf_clearance cookie in future Stage 1 requests for this domain"
                }
            print(f"[Scrape] Stage 4 returned None")
        except Exception as e:
            print(f"[Scrape] Stage 4 exception: {type(e).__name__}: {str(e)[:150]}")
            import traceback
            print(f"[Scrape] Traceback: {traceback.format_exc()[:200]}")
    else:
        print(f"[Scrape] Stage 4 is disabled")
    
    print(f"[Scrape] All stages failed!")
    raise HTTPException(status_code=503, detail="All stages failed. Try enabling Stage 4 or check if the site is accessible.")


if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", "7860"))
    uvicorn.run(app, host="0.0.0.0", port=port)