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 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
from fastapi import APIRouter, HTTPException, BackgroundTasks
from pydantic import BaseModel
from typing import List, Optional
import secrets
import uuid
import asyncio

from db import get_supabase

router = APIRouter(prefix="/qaz", tags=["Admin"])

# --- Models ---

class APIKey(BaseModel):
    id: str
    name: str
    token: str
    usage_tokens: int
    limit_tokens: int
    created_at: str
    is_active: bool

class CreateKeyRequest(BaseModel):
    name: str
    limit_tokens: Optional[int] = 1000000

class LookupKeyRequest(BaseModel):
    token: str

class PortalMessage(BaseModel):
    message: str

class PortalProviderRequest(BaseModel):
    provider: str  # "copilot", "huggingchat", "chatgpt", "gemini", "zai"

# --- Endpoints ---

@router.get("/keys", response_model=List[APIKey])
async def list_keys():
    """List all API keys."""
    supabase = get_supabase()
    if not supabase:
        raise HTTPException(status_code=503, detail="Database unavailable")
        
    try:
        res = supabase.table("kaiapi_api_keys").select("*").order("created_at", desc=True).execute()
        return res.data
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/keys", response_model=APIKey)
async def create_key(req: CreateKeyRequest):
    """Create a new API key."""
    supabase = get_supabase()
    if not supabase:
        raise HTTPException(status_code=503, detail="Database unavailable")
    
    # Generate a secure token
    token = f"sk-kai-{secrets.token_urlsafe(16)}"
    
    new_key = {
        "name": req.name,
        "token": token,
        "limit_tokens": req.limit_tokens,
        "usage_tokens": 0,
        "is_active": True
    }
    
    try:
        res = supabase.table("kaiapi_api_keys").insert(new_key).execute()
        if res.data:
            return res.data[0]
        raise HTTPException(status_code=500, detail="Failed to create key")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/keys/{key_id}")
async def revoke_key(key_id: str):
    """Revoke (delete) an API key."""
    supabase = get_supabase()
    if not supabase:
        raise HTTPException(status_code=503, detail="Database unavailable")
        
    try:
        # Check if exists first? Or just delete.
        # Hard delete for now, or soft delete if we had is_active column logic in router update, but delete is cleaner for management
        res = supabase.table("kaiapi_api_keys").delete().eq("id", key_id).execute()
        return {"status": "success", "deleted": key_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/keys/{key_id}/reset")
async def reset_usage(key_id: str):
    """Reset usage for a key."""
    supabase = get_supabase()
    if not supabase:
        raise HTTPException(status_code=503, detail="Database unavailable")
        
    try:
        supabase.table("kaiapi_api_keys").update({"usage_tokens": 0}).eq("id", key_id).execute()
        return {"status": "reset"}
    except Exception as e:
         raise HTTPException(status_code=500, detail=str(e))

@router.post("/keys/lookup")
async def lookup_key_by_token(req: LookupKeyRequest):
    """Lookup API key usage by token (for public dashboard)."""
    supabase = get_supabase()
    if not supabase:
        raise HTTPException(status_code=503, detail="Database unavailable")
    
    if not req.token or not req.token.startswith("sk-"):
        raise HTTPException(status_code=400, detail="Invalid token format")
    
    try:
        res = supabase.table("kaiapi_api_keys").select("*").eq("token", req.token).execute()
        
        if not res.data or len(res.data) == 0:
            raise HTTPException(status_code=404, detail="Key not found")
        
        key = res.data[0]
        
        # Return limited info (don't expose full token)
        return {
            "name": key.get("name"),
            "usage_tokens": key.get("usage_tokens", 0),
            "limit_tokens": key.get("limit_tokens", 0),
            "remaining": key.get("limit_tokens", 0) - key.get("usage_tokens", 0),
            "created_at": key.get("created_at"),
            "is_active": key.get("is_active", True)
        }
    except HTTPException:
        raise
    except Exception as e:
        error_msg = str(e)
        if hasattr(e, 'message'):
            error_msg = str(e.message)
        elif hasattr(e, 'args') and len(e.args) > 0:
            error_msg = str(e.args[0])
        raise HTTPException(status_code=500, detail=error_msg)

# --- Copilot CAPTCHA Handling ---

@router.get("/copilot/captcha/status")
async def copilot_captcha_status():
    """Check if Copilot has a pending CAPTCHA challenge."""
    try:
        from providers.copilot_provider import CopilotProvider
        
        is_pending = CopilotProvider.is_captcha_pending()
        
        if is_pending:
            # Check if screenshot exists
            import os
            screenshot_path = "/tmp/copilot_captcha.png"
            has_screenshot = os.path.exists(screenshot_path)
            
            return {
                "captcha_required": True,
                "has_screenshot": has_screenshot,
                "screenshot_url": "/qaz/copilot/captcha/screenshot" if has_screenshot else None,
                "message": "CAPTCHA verification required. Please solve it in the admin panel."
            }
        else:
            return {
                "captcha_required": False,
                "message": "No CAPTCHA pending"
            }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/copilot/captcha/screenshot")
async def copilot_captcha_screenshot():
    """Get the CAPTCHA screenshot for solving."""
    import os
    from fastapi.responses import FileResponse
    
    screenshot_path = "/tmp/copilot_captcha.png"
    
    if not os.path.exists(screenshot_path):
        raise HTTPException(status_code=404, detail="No CAPTCHA screenshot available")
    
    return FileResponse(screenshot_path, media_type="image/png")

@router.post("/copilot/captcha/solved")
async def copilot_captcha_solved():
    """Mark CAPTCHA as solved and save session."""
    try:
        from providers.copilot_provider import CopilotProvider
        from copilot_session import CopilotSessionManager
        
        # Get the context with CAPTCHA
        context = CopilotProvider.get_captcha_context()
        
        if not context:
            raise HTTPException(status_code=400, detail="No CAPTCHA context found")
        
        # Wait a bit for user to solve
        await asyncio.sleep(2)
        
        # Save cookies from the solved session
        cookies = await context.cookies()
        session_mgr = CopilotSessionManager()
        session_mgr.save_cookies(cookies)
        
        # Clear the pending state
        CopilotProvider.clear_captcha_pending()
        
        # Close the context
        await context.close()
        
        return {
            "status": "success",
            "message": "CAPTCHA solved and session saved"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/copilot/captcha/clear")
async def copilot_captcha_clear():
    """Clear the CAPTCHA pending state (for retry)."""
    try:
        from providers.copilot_provider import CopilotProvider
        
        # Get context and close it
        context = CopilotProvider.get_captcha_context()
        if context:
            await context.close()
        
        CopilotProvider.clear_captcha_pending()
        
        return {
            "status": "success",
            "message": "CAPTCHA state cleared"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/copilot/session/status")
async def copilot_session_status():
    """Check Copilot session status."""
    try:
        from copilot_session import CopilotSessionManager
        
        session_info = CopilotSessionManager.get_session_info()
        return session_info
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# --- Interactive Copilot Portal ---

@router.post("/copilot/portal/start")
async def start_copilot_portal():
    """Start the interactive Copilot browser portal."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        await portal.initialize()
        
        return {
            "status": "success",
            "message": "Portal started successfully",
            "initialized": portal.is_initialized
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/copilot/portal/screenshot")
async def get_portal_screenshot():
    """Get the latest portal screenshot."""
    import os
    from fastapi.responses import FileResponse
    
    try:
        from copilot_portal import get_portal
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        # Take fresh screenshot
        await portal.take_screenshot()
        
        screenshot_path = "/tmp/copilot_portal.png"
        if not os.path.exists(screenshot_path):
            raise HTTPException(status_code=404, detail="Screenshot not available")
        
        return FileResponse(screenshot_path, media_type="image/png")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/copilot/portal/send")
async def send_portal_message(req: PortalMessage):
    """Send a message through the portal."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        response = await portal.send_message(req.message)
        
        return {
            "status": "success",
            "response": response
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/copilot/portal/newchat")
async def portal_new_chat():
    """Click New Chat button in the portal."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        await portal.click_new_chat()
        
        return {
            "status": "success",
            "message": "New chat clicked"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/copilot/portal/refresh")
async def portal_refresh():
    """Refresh the portal page."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        await portal.refresh_page()
        
        return {
            "status": "success",
            "message": "Page refreshed"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/copilot/portal/close")
async def close_copilot_portal():
    """Close the portal browser."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        await portal.close()
        
        return {
            "status": "success",
            "message": "Portal closed"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/copilot/portal/status")
async def get_portal_status():
    """Check if the portal is currently running."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        is_running = portal.is_running()
        
        return {
            "is_running": is_running,
            "is_initialized": portal.is_initialized
        }
    except Exception as e:
        return {
            "is_running": False,
            "is_initialized": False,
            "error": str(e)
        }


class PortalClick(BaseModel):
    x: float
    y: float

@router.post("/copilot/portal/click")
async def portal_click(req: PortalClick):
    """Click at specific coordinates on the portal page."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        await portal.click_at_coordinates(req.x, req.y)
        
        return {
            "status": "success",
            "message": f"Clicked at coordinates ({req.x}, {req.y})"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/copilot/portal/click_checkbox")
async def portal_click_checkbox():
    """Click on the CAPTCHA checkbox (estimated position)."""
    try:
        from copilot_portal import get_portal
        
        portal = get_portal()
        
        if not portal.is_initialized:
            raise HTTPException(status_code=400, detail="Portal not initialized. Start it first.")
        
        # CAPTCHA checkbox is typically in the center of the screen
        # Based on 1280x800 viewport, center is approximately (640, 400)
        # The checkbox in your screenshot appears to be slightly above center
        await portal.click_at_coordinates(640, 350)
        
        return {
            "status": "success",
            "message": "Clicked CAPTCHA checkbox area"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- NEW: Unified Browser Portal System for ALL Providers ---

class UnifiedPortalAction(BaseModel):
    provider: str  # "copilot", "huggingchat", "chatgpt", "gemini", "zai"
    action: str    # "click", "type", "keypress", "scroll", "focus"
    x: Optional[float] = None
    y: Optional[float] = None
    text: Optional[str] = None
    key: Optional[str] = None
    delta_x: Optional[int] = 0
    delta_y: Optional[int] = 0

@router.post("/portal/start")
async def start_unified_portal(req: PortalProviderRequest):
    """Start an interactive browser portal for any provider."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        provider = PortalProvider(req.provider.lower())
        portal = get_portal_manager().get_portal(provider)
        
        if portal.is_running():
            return {
                "status": "already_running",
                "provider": req.provider,
                "message": f"{provider.value} portal is already running"
            }
        
        await portal.initialize(headless=True)
        
        return {
            "status": "success",
            "provider": req.provider,
            "message": f"{provider.value} portal started successfully",
            "requires_login": portal.config.requires_login,
            "url": portal.config.url
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/portal/{provider}/screenshot")
async def get_unified_portal_screenshot(provider: str, quality: float = 1.0, format: str = "png"):
    """Get screenshot from any provider portal with optional quality/compression."""
    import os
    from fastapi.responses import FileResponse, StreamingResponse
    from PIL import Image
    import io
    
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running. Start it first.")
        
        await portal.take_screenshot()
        
        if not os.path.exists(portal.screenshot_path):
            raise HTTPException(status_code=404, detail="Screenshot not available")
        
        # If quality is 1.0 and format is png, return as-is
        if quality >= 1.0 and format == "png":
            return FileResponse(portal.screenshot_path, media_type="image/png")
        
        # Otherwise, compress/process the image
        img = Image.open(portal.screenshot_path)
        
        # Resize if quality < 1.0
        if quality < 1.0:
            new_size = (int(img.width * quality), int(img.height * quality))
            img = img.resize(new_size, Image.Resampling.LANCZOS)
        
        # Convert to desired format
        img_io = io.BytesIO()
        if format == "jpeg" or format == "jpg":
            img = img.convert("RGB")
            img.save(img_io, format="JPEG", quality=int(quality * 100) if quality < 1 else 85)
            media_type = "image/jpeg"
        else:
            img.save(img_io, format="PNG")
            media_type = "image/png"
        
        img_io.seek(0)
        return StreamingResponse(img_io, media_type=media_type)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# MJPEG Streaming endpoint for video-like experience
@router.get("/portal/{provider}/stream")
async def stream_portal_video(provider: str, quality: float = 0.5, fps: int = 2):
    """Stream the portal as MJPEG for video-like experience."""
    import os
    import asyncio
    from fastapi.responses import StreamingResponse
    from PIL import Image
    import io
    
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running")
        
        async def generate_frames():
            """Generate MJPEG stream."""
            frame_delay = 1.0 / fps
            
            while portal.is_running():
                try:
                    # Take screenshot
                    await portal.take_screenshot()
                    
                    if os.path.exists(portal.screenshot_path):
                        # Process image
                        img = Image.open(portal.screenshot_path)
                        
                        if quality < 1.0:
                            new_size = (int(img.width * quality), int(img.height * quality))
                            img = img.resize(new_size, Image.Resampling.LANCZOS)
                        
                        # Convert to JPEG for smaller size
                        img = img.convert("RGB")
                        img_io = io.BytesIO()
                        img.save(img_io, format="JPEG", quality=70)
                        img_io.seek(0)
                        
                        frame_data = img_io.getvalue()
                        
                        # Yield MJPEG frame
                        yield (
                            b'--frame\r\n'
                            b'Content-Type: image/jpeg\r\n'
                            b'Content-Length: ' + str(len(frame_data)).encode() + b'\r\n'
                            b'\r\n' + frame_data + b'\r\n'
                        )
                    
                    await asyncio.sleep(frame_delay)
                    
                except Exception as e:
                    print(f"Stream error: {e}")
                    await asyncio.sleep(frame_delay)
        
        return StreamingResponse(
            generate_frames(),
            media_type="multipart/x-mixed-replace;boundary=frame"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/action")
async def unified_portal_action(req: UnifiedPortalAction):
    """Perform an action on any provider portal."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        provider = PortalProvider(req.provider.lower())
        portal = get_portal_manager().get_portal(provider)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{req.provider} portal not running. Start it first.")
        
        result = {}
        
        if req.action == "click":
            if req.x is None or req.y is None:
                raise HTTPException(status_code=400, detail="x and y coordinates required for click")
            await portal.click(req.x, req.y)
            result = {"message": f"Clicked at ({req.x}, {req.y})"}
            
        elif req.action == "type":
            if not req.text:
                raise HTTPException(status_code=400, detail="text required for type action")
            await portal.type_text(req.text)
            result = {"message": f"Typed: {req.text[:50]}..." if len(req.text) > 50 else f"Typed: {req.text}"}
            
        elif req.action == "keypress":
            if not req.key:
                raise HTTPException(status_code=400, detail="key required for keypress action")
            await portal.key_press(req.key)
            result = {"message": f"Pressed key: {req.key}"}
            
        elif req.action == "scroll":
            await portal.scroll(req.delta_x or 0, req.delta_y or 0)
            result = {"message": f"Scrolled by ({req.delta_x}, {req.delta_y})"}
            
        elif req.action == "focus":
            if req.x is None or req.y is None:
                raise HTTPException(status_code=400, detail="x and y coordinates required for focus")
            await portal.focus_input(req.x, req.y)
            result = {"message": f"Focused input at ({req.x}, {req.y})"}
            
        else:
            raise HTTPException(status_code=400, detail=f"Unknown action: {req.action}")
        
        return {
            "status": "success",
            "provider": req.provider,
            "action": req.action,
            **result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/{provider}/send")
async def unified_portal_send_message(provider: str, req: PortalMessage):
    """Send a message through any provider portal."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running. Start it first.")
        
        response = await portal.send_message(req.message)
        
        return {
            "status": "success",
            "provider": provider,
            "response": response
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/{provider}/newchat")
async def unified_portal_new_chat(provider: str):
    """Start new chat on any provider portal."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running. Start it first.")
        
        await portal.new_chat()
        
        return {
            "status": "success",
            "provider": provider,
            "message": "New chat started"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/{provider}/close")
async def close_unified_portal(provider: str):
    """Close any provider portal."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        await portal.close()
        
        return {
            "status": "success",
            "provider": provider,
            "message": f"{provider} portal closed"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/portal/status")
async def get_all_portal_status():
    """Get status of all provider portals."""
    try:
        from browser_portal import get_portal_manager, PORTAL_CONFIGS
        
        manager = get_portal_manager()
        active_portals = manager.get_active_portals()
        
        all_providers = []
        for provider in PORTAL_CONFIGS.keys():
            is_running = provider in active_portals
            config = PORTAL_CONFIGS[provider]
            all_providers.append({
                "provider": provider.value,
                "name": config.name,
                "is_running": is_running,
                "requires_login": config.requires_login,
                "url": config.url
            })
        
        return {
            "providers": all_providers,
            "active_count": len(active_portals)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- Browser Navigation Controls ---

@router.post("/portal/{provider}/back")
async def browser_go_back(provider: str):
    """Go back in browser history."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running")
        
        success = await portal.go_back()
        url = await portal.get_current_url()
        
        return {
            "status": "success" if success else "error",
            "provider": provider,
            "current_url": url,
            "message": "Navigated back" if success else "Could not go back"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/{provider}/forward")
async def browser_go_forward(provider: str):
    """Go forward in browser history."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running")
        
        success = await portal.go_forward()
        url = await portal.get_current_url()
        
        return {
            "status": "success" if success else "error",
            "provider": provider,
            "current_url": url,
            "message": "Navigated forward" if success else "Could not go forward"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

class NavigateRequest(BaseModel):
    url: str

@router.post("/portal/{provider}/navigate")
async def browser_navigate(provider: str, req: NavigateRequest):
    """Navigate to a specific URL."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running")
        
        success = await portal.goto_url(req.url)
        url = await portal.get_current_url()
        title = await portal.get_page_title()
        
        return {
            "status": "success" if success else "error",
            "provider": provider,
            "url": url,
            "title": title,
            "message": f"Navigated to {req.url}" if success else f"Failed to navigate to {req.url}"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/portal/{provider}/info")
async def get_browser_info(provider: str):
    """Get current browser page info (URL and title)."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail=f"{provider} portal not running")
        
        url = await portal.get_current_url()
        title = await portal.get_page_title()
        
        return {
            "status": "success",
            "provider": provider,
            "url": url,
            "title": title
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- Proxy Management for Browser Portals ---

@router.post("/proxy/fetch")
async def fetch_new_proxies():
    """Fetch new free proxies and test them."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        
        # Fetch new proxies
        proxies = await proxy_mgr.fetch_proxies(limit=30)
        
        # Test first few to find a working one
        working_proxy = await proxy_mgr.get_working_proxy(max_attempts=5)
        
        stats = proxy_mgr.get_proxy_stats()
        
        return {
            "status": "success",
            "message": f"Fetched {len(proxies)} proxies",
            "working_proxy": str(working_proxy) if working_proxy else None,
            "stats": stats
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/proxy/rotate")
async def rotate_proxy():
    """Rotate to a new working proxy."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        
        # Rotate to new proxy
        new_proxy = await proxy_mgr.rotate_proxy()
        
        if new_proxy:
            return {
                "status": "success",
                "proxy": str(new_proxy),
                "country": new_proxy.country,
                "response_time": f"{new_proxy.response_time:.2f}s"
            }
        else:
            raise HTTPException(status_code=503, detail="No working proxy available")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/proxy/status")
async def get_proxy_status():
    """Get current proxy status."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        
        stats = proxy_mgr.get_proxy_stats()
        current = proxy_mgr.get_current_proxy()
        
        return {
            "current_proxy": str(current) if current else None,
            **stats
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/proxy/test")
async def test_current_proxy():
    """Test if current proxy is working."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        current = proxy_mgr.get_current_proxy()
        
        if not current:
            raise HTTPException(status_code=400, detail="No proxy currently set")
        
        is_working = await proxy_mgr.test_proxy(current)
        
        return {
            "status": "success",
            "proxy": str(current),
            "is_working": is_working,
            "response_time": f"{current.response_time:.2f}s" if is_working else None
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/portal/{provider}/restart-with-proxy")
async def restart_portal_with_proxy(provider: str):
    """Restart portal with current proxy."""
    try:
        from browser_portal import get_portal_manager, PortalProvider
        from proxy_manager import get_proxy_manager
        
        prov = PortalProvider(provider.lower())
        portal = get_portal_manager().get_portal(prov)
        proxy_mgr = get_proxy_manager()
        
        # Get current proxy
        current_proxy = proxy_mgr.get_current_proxy()
        if not current_proxy:
            raise HTTPException(status_code=503, detail="No custom proxy configured. Set one first.")
        
        # Close existing portal
        await portal.close()
        
        # Reinitialize with proxy
        await portal.initialize(headless=True, proxy=current_proxy)
        
        return {
            "status": "success",
            "provider": provider,
            "proxy": str(current_proxy),
            "message": f"{provider} portal restarted with proxy {current_proxy.ip}"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- Provider Toggle Management ---

class ProviderToggleRequest(BaseModel):
    provider_id: str
    enabled: bool

@router.get("/providers")
async def get_providers():
    """Get all providers with their enabled/disabled status."""
    try:
        from provider_state import get_provider_state_manager
        
        manager = await get_provider_state_manager()
        providers = manager.get_all_providers()
        
        return {
            "providers": [
                {
                    "id": provider_id,
                    "name": config["name"],
                    "type": config["type"],
                    "enabled": config["enabled"]
                }
                for provider_id, config in providers.items()
            ]
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/providers/toggle")
async def toggle_provider(req: ProviderToggleRequest):
    """Enable or disable a provider."""
    try:
        from provider_state import get_provider_state_manager
        
        manager = await get_provider_state_manager()
        success = await manager.set_provider_state(req.provider_id, req.enabled)
        
        if success:
            return {
                "status": "success",
                "provider_id": req.provider_id,
                "enabled": req.enabled,
                "message": f"Provider '{req.provider_id}' {'enabled' if req.enabled else 'disabled'}"
            }
        else:
            raise HTTPException(status_code=400, detail=f"Failed to toggle provider '{req.provider_id}'")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- Custom Proxy Management ---

class SetProxyRequest(BaseModel):
    proxy: str  # Format: ip:port or protocol://ip:port or protocol://user:pass@ip:port
    username: Optional[str] = None  # Optional username for proxy auth
    password: Optional[str] = None  # Optional password for proxy auth

@router.post("/proxy/set")
async def set_custom_proxy(req: SetProxyRequest):
    """Set a custom proxy for the entire container with optional authentication."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        success = proxy_mgr.set_custom_proxy(req.proxy, req.username, req.password)
        
        if success:
            status = proxy_mgr.get_status()
            return {
                "status": "success",
                "proxy": status["proxy"],
                "has_auth": status.get("has_auth", False),
                "username": status.get("username"),
                "message": "Custom proxy set successfully"
            }
        else:
            raise HTTPException(status_code=400, detail="Invalid proxy format")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/proxy/clear")
async def clear_custom_proxy():
    """Clear the custom proxy."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        proxy_mgr.clear_proxy()
        
        return {
            "status": "success",
            "message": "Custom proxy cleared"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/proxy/status")
async def get_proxy_status():
    """Get current proxy status."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        status = proxy_mgr.get_status()
        
        return status
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/proxy/test")
async def test_custom_proxy():
    """Test if the current custom proxy is working."""
    try:
        from proxy_manager import get_proxy_manager
        
        proxy_mgr = get_proxy_manager()
        
        if not proxy_mgr.get_current_proxy():
            raise HTTPException(status_code=400, detail="No custom proxy configured")
        
        is_working = await proxy_mgr.test_proxy()
        status = proxy_mgr.get_status()
        
        return {
            "status": "success",
            "is_working": is_working,
            **status
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- Saved Proxies Management ---

class ProxyCreateRequest(BaseModel):
    name: Optional[str] = None
    ip: str
    port: int
    protocol: str = "http"
    username: Optional[str] = None
    password: Optional[str] = None
    country: Optional[str] = None
    city: Optional[str] = None
    notes: Optional[str] = None

@router.get("/proxies")
async def list_proxies():
    """Get all saved proxies from Supabase."""
    try:
        from db import get_supabase
        
        supabase = get_supabase()
        if not supabase:
            return {"proxies": []}
        
        res = supabase.table("kaiapi_proxies").select("*").order("created_at", desc=True).execute()
        return {"proxies": res.data or []}
    except Exception as e:
        logger.error(f"Failed to list proxies: {e}")
        return {"proxies": []}

@router.post("/terminal/sync-auth")
async def sync_terminal_auth(req: dict):
    """Sync OpenCode auth to Supabase."""
    try:
        from opencode_terminal import get_terminal_manager
        
        manager = get_terminal_manager()
        # Just use the default model to get an instance
        portal = manager.get_portal("opencode-kimi-k2.5-free") 
        success = await portal.sync_auth()
        
        if success:
            return {"status": "success", "message": "Auth synced to Supabase"}
        else:
            return {"status": "error", "message": "Failed to sync auth (check logs)"}
            
    except Exception as e:
        logger.error(f"Error syncing auth: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/proxies")
async def create_proxy(req: ProxyCreateRequest):
    """Add a new proxy to Supabase."""
    try:
        from db import get_supabase
        
        supabase = get_supabase()
        if not supabase:
            raise HTTPException(status_code=503, detail="Database unavailable")
        
        proxy_data = {
            "name": req.name,
            "ip": req.ip,
            "port": req.port,
            "protocol": req.protocol,
            "username": req.username,
            "password": req.password,
            "country": req.country,
            "city": req.city,
            "notes": req.notes,
            "is_active": False
        }
        
        res = supabase.table("kaiapi_proxies").insert(proxy_data).execute()
        
        return {
            "status": "success",
            "message": "Proxy saved",
            "proxy": res.data[0] if res.data else None
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/proxies/{proxy_id}/activate")
async def activate_proxy(proxy_id: int):
    """Activate a saved proxy."""
    try:
        from db import get_supabase
        from proxy_manager import get_proxy_manager
        
        supabase = get_supabase()
        if not supabase:
            raise HTTPException(status_code=503, detail="Database unavailable")
        
        res = supabase.table("kaiapi_proxies").select("*").eq("id", proxy_id).execute()
        if not res.data:
            raise HTTPException(status_code=404, detail="Proxy not found")
        
        proxy = res.data[0]
        
        # Deactivate all first
        supabase.table("kaiapi_proxies").update({"is_active": False}).neq("id", proxy_id).execute()
        
        # Activate this one
        supabase.table("kaiapi_proxies").update({"is_active": True}).eq("id", proxy_id).execute()
        
        # Set as current
        proxy_mgr = get_proxy_manager()
        proxy_str = f"{proxy['protocol']}://{proxy['ip']}:{proxy['port']}"
        proxy_mgr.set_custom_proxy(proxy_str, proxy.get("username"), proxy.get("password"))
        
        return {"status": "success", "message": f"Proxy activated"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/proxies/{proxy_id}")
async def delete_proxy(proxy_id: int):
    """Delete a saved proxy."""
    try:
        from db import get_supabase
        
        supabase = get_supabase()
        if not supabase:
            raise HTTPException(status_code=503, detail="Database unavailable")
        
        supabase.table("kaiapi_proxies").delete().eq("id", proxy_id).execute()
        
        return {"status": "success", "message": "Proxy deleted"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# --- OpenCode Terminal Portal ---

class TerminalInput(BaseModel):
    text: str

class TerminalKey(BaseModel):
    key: str

@router.post("/terminal/start")
async def start_terminal(req: dict):
    """Start OpenCode terminal session."""
    try:
        from opencode_terminal import get_terminal_manager
        
        model = req.get("model", "kimi-k2.5-free")
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        if portal.is_running():
            return {
                "status": "already_running",
                "model": model,
                "message": f"Terminal for {model} is already running"
            }
        
        await portal.initialize()
        
        return {
            "status": "success",
            "model": model,
            "message": f"Terminal started for {model}"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/terminal/output")
async def get_terminal_output(model: str = "kimi-k2.5-free", lines: int = 100):
    """Get recent terminal output."""
    try:
        from opencode_terminal import get_terminal_manager
        
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        if not portal.is_running():
            return {"lines": [], "status": "stopped"}
            
        output_lines = portal.get_output(max_lines=lines)
        
        # Format for frontend
        formatted_lines = [
            {"type": stream, "content": line} 
            for stream, line in output_lines
        ]
        
        return {
            "lines": formatted_lines,
            "status": "running"
        }
    except Exception as e:
        return {"lines": [], "error": str(e), "status": "error"}

@router.post("/terminal/input")
async def send_terminal_input(req: TerminalInput, model: str = "kimi-k2.5-free"):
    """Send text input to terminal."""
    try:
        from opencode_terminal import get_terminal_manager
        
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail="Terminal not running")
            
        success = await portal.send_input(req.text)
        
        return {"status": "success" if success else "error"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/terminal/key")
async def send_terminal_key(req: TerminalKey, model: str = "kimi-k2.5-free"):
    """Send special key to terminal."""
    try:
        from opencode_terminal import get_terminal_manager
        
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail="Terminal not running")
            
        success = await portal.send_key(req.key)
        
        return {"status": "success" if success else "error"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/terminal/close")
async def close_terminal(req: dict):
    """Close terminal session."""
    try:
        from opencode_terminal import get_terminal_manager
        
        model = req.get("model", "kimi-k2.5-free")
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        await portal.close()
        
        return {"status": "success", "message": "Terminal closed"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/terminal/reset")
async def reset_terminal(req: dict):
    """Manually trigger a full disposable reset (wipes all traces and starts fresh)."""
    try:
        from opencode_terminal import get_terminal_manager
        
        model = req.get("model", "kimi-k2.5-free")
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        if not portal.is_running():
            raise HTTPException(status_code=400, detail="Terminal not running")
        
        success = await portal.manual_reset()
        
        return {
            "status": "success" if success else "error",
            "message": "Full disposable reset completed - OpenCode sees a brand new device!",
            "model": model
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/terminal/status")
async def get_terminal_status(model: str = "kimi-k2.5-free"):
    """Get disposable mode status and message count."""
    try:
        from opencode_terminal import get_terminal_manager
        
        manager = get_terminal_manager()
        portal = manager.get_portal(model)
        
        status = portal.get_disposable_status()
        
        return {
            "status": "success",
            "data": status
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))