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
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
from fastapi import FastAPI, HTTPException, Request, UploadFile, File, Depends, Header
from fastapi.responses import StreamingResponse, HTMLResponse, Response
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
import httpx
import os
import json
import logging
from datetime import datetime

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(
    title="OMNIAPI Services",
    description="Professional AI Services - Chat Completions, Image Generation, Web Search, Speech-To-Text, and Text-to-Speech",
    version="1.0.0",
    servers=[
        {
            "url": "https://at41rv-a77.hf.space",
            "description": "Production server"
        }
    ],
    swagger_ui_parameters={"defaultModelsExpandDepth": -1}
)

# Get HF token from environment variable
HF_TOKEN = os.getenv("HF_TOKEN")
BACKEND_URL = "https://at41rv-a77backend.hf.space"
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN", "")  # Set this in your HF Space secrets

if not HF_TOKEN:
    logger.warning("HF_TOKEN not found in environment variables")

security = HTTPBearer()

# In-memory storage for generated API keys with metadata
generated_api_keys = {}  # Changed from set to dict
user_api_keys = {}  # Track API keys per user (by IP or session)

async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """
    Verify the access token from the Authorization header
    Accepts both the original ACCESS_TOKEN and forwards to backend for validation
    """
    token = credentials.credentials
    
    # Check if it's the original access token
    if ACCESS_TOKEN and token == ACCESS_TOKEN:
        return token
    
    # Attempt to forward the token to backend for validation
    try:
        response = await make_backend_request("/validate-token", "POST", {"token": token})
        if response.status_code == 200:
            data = response.json()
            if data.get("valid", False):
                return token
            else:
                logger.error(f"Token validation failed: Backend response indicates token is invalid. Response: {data}")
                raise HTTPException(status_code=401, detail="Invalid access token. Backend validation failed.")
        elif response.status_code == 404:
            logger.warning(f"Token validation endpoint not found (404). Skipping validation and using token directly. Response: {response.text}")
            return token  # Skip validation if endpoint is not found, allow token to be used directly
        else:
            logger.error(f"Token validation failed: Backend returned status code {response.status_code}. Response: {response.text}")
            raise HTTPException(status_code=401, detail=f"Invalid access token. Backend returned status {response.status_code}.")
    except Exception as e:
        logger.error(f"Token validation error: {str(e)}")
        raise HTTPException(status_code=401, detail=f"Invalid access token. Validation error: {str(e)}")

# Request timeout configuration
REQUEST_TIMEOUT = 60.0

# Pydantic models for requests (OpenAI Compatible)
class Message(BaseModel):
    role: str = Field(..., description="Role of the message sender", example="user")
    content: str = Field(..., description="Content of the message", example="Hello, how are you?")

class SimpleChatRequest(BaseModel):
    model: str = Field(..., description="AI model to use for completion", example="gpt-4o")
    prompt: str = Field(None, nullable=True, description="Text prompt for the AI to respond to (legacy)", example="Explain quantum computing in simple terms")
    messages: List[Message] = Field(None, nullable=True, description="List of messages for OpenAI-compatible chat")
    system_prompt: str = Field(
        default="You are a helpful AI assistant.",
        nullable=True,
        description="System prompt to set AI behavior and personality",
        example="You are a helpful physics teacher who explains complex topics simply."
    )
    max_tokens: int = Field(default=2048, nullable=True, description="Maximum tokens to generate", example=2048)
    temperature: float = Field(default=0.7, nullable=True, description="Temperature for response randomness", example=0.7)
    stream: bool = Field(default=False, nullable=True, description="Whether to stream the response", example=False)

class GenerationRequest(BaseModel):
    prompt: str = Field(..., description="Text description of the image to generate", example="A beautiful sunset over mountains")
    model: str = Field(..., description="Image generation model to use", example="flux.1-dev")
    size: str = Field(default="1024x1024", nullable=True, description="Image size", example="1024x1024")

class SearchRequest(BaseModel):
    query: str = Field(..., description="Search query", example="artificial intelligence")
    max_results: int = Field(default=10, nullable=True, description="Maximum number of results", example=10)
    region: str = Field(default="us", nullable=True, description="Search region", example="us")
    safesearch: str = Field(default="moderate", nullable=True, description="Safe search level", example="moderate")
    max_chars: int = Field(default=2000, nullable=True, description="Maximum characters to scrape from URL", example=2000)

class TTSRequest(BaseModel):
    text: str = Field(..., description="Text to convert to speech", example="Hello, this is a test message")
    provider: str = Field(..., description="TTS provider to use", example="GesseritTTS")
    voice: str = Field(..., description="Voice to use for TTS", example="Emma")

class APIKeyCreateRequest(BaseModel):
    name: str = Field(..., min_length=1, max_length=50, description="Name for the API key", example="My API Key")

class APIKeyResponse(BaseModel):
    success: bool = Field(..., description="Whether the operation was successful", example=True)
    api_key: str = Field(..., description="Generated API key", example="oa1234567890abcdef...")
    name: str = Field(default="", nullable=True, description="Name of the API key", example="My API Key")
    message: str = Field(..., description="Response message", example="API key generated successfully")
    created_at: str = Field(..., description="Creation timestamp", example="2024-01-20 10:30:00 UTC")
    expires: str = Field(default="Never", description="Expiration date", example="Never")
    usage_note: str = Field(..., description="Usage instructions", example="Include this API key in the Authorization header")

class APIKeyInfo(BaseModel):
    key: str = Field(..., description="API key (full or masked)", example="oa1234567890abcdef...")
    name: str = Field(..., description="Name of the API key", example="My API Key")
    created_at: str = Field(..., description="Creation timestamp", example="2024-01-20 10:30:00 UTC")
    last_used: Optional[str] = Field(None, description="Last used timestamp", example="2024-01-20 15:45:00 UTC")
    usage_count: int = Field(..., description="Number of times used", example=42)
    key_preview: str = Field(..., description="Masked preview of the key", example="oa1234...********")

class UserAPIKeysResponse(BaseModel):
    success: bool = Field(..., description="Whether the operation was successful", example=True)
    keys: List[APIKeyInfo] = Field(..., description="List of user's API keys")
    total_keys: int = Field(..., description="Total number of keys", example=2)
    max_keys: int = Field(default=3, description="Maximum allowed keys", example=3)
    remaining_slots: int = Field(..., description="Remaining key slots", example=1)

class APIKeyDeleteResponse(BaseModel):
    success: bool = Field(..., description="Whether the operation was successful", example=True)
    message: str = Field(..., description="Response message", example="API key deleted successfully")

async def make_backend_request(
    endpoint: str, 
    method: str = "GET", 
    data: dict = None,
    params: dict = None,
    files: dict = None,
    timeout: float = REQUEST_TIMEOUT
) -> httpx.Response:
    """Make authenticated request to backend API"""
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "User-Agent": "OMNIAPI-Proxy/1.0"
    }
    
    # Only add Content-Type for JSON requests
    if not files:
        headers["Content-Type"] = "application/json"
    
    try:
        async with httpx.AsyncClient(timeout=timeout) as client:
            if method.upper() == "GET":
                response = await client.get(
                    f"{BACKEND_URL}{endpoint}",
                    headers=headers,
                    params=params
                )
            elif method.upper() == "POST":
                if files:
                    # For file uploads, don't set Content-Type (let httpx handle multipart)
                    headers.pop("Content-Type", None)
                    response = await client.post(
                        f"{BACKEND_URL}{endpoint}",
                        headers=headers,
                        files=files,
                        params=params
                    )
                else:
                    response = await client.post(
                        f"{BACKEND_URL}{endpoint}",
                        headers=headers,
                        json=data,
                        params=params
                    )
            elif method.upper() == "DELETE":
                response = await client.delete(
                    f"{BACKEND_URL}{endpoint}",
                    headers=headers,
                    params=params
                )
            else:
                raise HTTPException(status_code=405, detail="Method not allowed")
            
            return response
            
    except httpx.TimeoutException:
        logger.error(f"Request timeout to {endpoint}")
        raise HTTPException(status_code=504, detail="Backend request timeout")
    except httpx.RequestError as e:
        logger.error(f"Request error to {endpoint}: {str(e)}")
        raise HTTPException(status_code=502, detail="Backend connection error")
    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")

@app.get("/")
async def root():
    """Root endpoint returning OpenAPI specification"""
    return {
        "openapi": "3.0.0",
        "info": {
            "title": "OMNIAPI Services",
            "description": "Professional AI Services - Chat Completions, Image Generation, Web Search, Speech-To-Text, and Text-to-Speech",
            "version": "1.0.0"
        },
        "servers": [
            {
                "url": "https://at41rv-a77.hf.space",
                "description": "Production server"
            }
        ],
        "paths": {
            "/": {
                "get": {
                    "summary": "Root endpoint returning OpenAPI specification",
                    "responses": {
                        "200": {
                            "description": "OpenAPI specification",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/health": {
                "get": {
                    "summary": "Health check endpoint",
                    "responses": {
                        "200": {
                            "description": "Service health status"
                        }
                    }
                }
            },
            "/models": {
                "get": {
                    "summary": "Get available chat models",
                    "security": [{"bearerAuth": []}],
                    "responses": {
                        "200": {
                            "description": "List of available models"
                        }
                    }
                }
            },
            "/chat/completions": {
                "post": {
                    "summary": "Chat completions (OpenAI Compatible)",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "model": {"type": "string"},
                                        "messages": {
                                            "type": "array",
                                            "items": {
                                                "type": "object",
                                                "properties": {
                                                    "role": {"type": "string"},
                                                    "content": {"type": "string"}
                                                }
                                            }
                                        },
                                        "max_tokens": {"type": "integer"},
                                        "temperature": {"type": "number"},
                                        "stream": {"type": "boolean"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Chat completion response"
                        }
                    }
                }
            },
            "/image/generate": {
                "post": {
                    "summary": "Generate images",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "prompt": {"type": "string"},
                                        "model": {"type": "string"},
                                        "size": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Generated image response"
                        }
                    }
                }
            },
            "/web/search": {
                "post": {
                    "summary": "Web search",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "query": {"type": "string"},
                                        "max_results": {"type": "integer"},
                                        "region": {"type": "string"},
                                        "safesearch": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Search results"
                        }
                    }
                }
            },
            "/image/search": {
                "post": {
                    "summary": "Image search",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "query": {"type": "string"},
                                        "max_results": {"type": "integer"},
                                        "region": {"type": "string"},
                                        "safesearch": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Image search results"
                        }
                    }
                }
            },
            "/videos/search": {
                "post": {
                    "summary": "Video search",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "query": {"type": "string"},
                                        "max_results": {"type": "integer"},
                                        "region": {"type": "string"},
                                        "safesearch": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Video search results"
                        }
                    }
                }
            },
            "/tts/{provider}/voices": {
                "get": {
                    "summary": "Get TTS voices for provider",
                    "security": [{"bearerAuth": []}],
                    "parameters": [
                        {
                            "name": "provider",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"}
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Available voices"
                        }
                    }
                }
            },
            "/tts/generate": {
                "post": {
                    "summary": "Generate TTS audio",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "text": {"type": "string"},
                                        "provider": {"type": "string"},
                                        "voice": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Generated audio response"
                        }
                    }
                }
            },
            "/transcribe": {
                "post": {
                    "summary": "Audio transcription",
                    "security": [{"bearerAuth": []}],
                    "requestBody": {
                        "required": True,
                        "content": {
                            "multipart/form-data": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "audio_file": {
                                            "type": "string",
                                            "format": "binary"
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "Transcription result"
                        }
                    }
                }
            },
            "/audio/{audio_id}": {
                "get": {
                    "summary": "Serve audio file",
                    "security": [{"bearerAuth": []}],
                    "parameters": [
                        {
                            "name": "audio_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"}
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Audio file",
                            "content": {
                                "audio/mpeg": {
                                    "schema": {
                                        "type": "string",
                                        "format": "binary"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/image/{image_id}": {
                "get": {
                    "summary": "Serve image file",
                    "security": [{"bearerAuth": []}],
                    "parameters": [
                        {
                            "name": "image_id",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"}
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Image file",
                            "content": {
                                "image/jpeg": {
                                    "schema": {
                                        "type": "string",
                                        "format": "binary"
                                    }
                                }
                            }
                        }
                    }
                }
            },
            "/generate-api-key": {
                "post": {
                    "summary": "Generate a new API key",
                    "requestBody": {
                        "required": True,
                        "content": {
                            "application/json": {
                                "schema": {
                                    "type": "object",
                                    "properties": {
                                        "name": {"type": "string"}
                                    }
                                }
                            }
                        }
                    },
                    "responses": {
                        "200": {
                            "description": "API key generated successfully"
                        }
                    }
                }
            },
            "/api-keys/list": {
                "get": {
                    "summary": "List user API keys",
                    "responses": {
                        "200": {
                            "description": "List of user API keys"
                        }
                    }
                }
            },
            "/api-keys/{api_key}": {
                "delete": {
                    "summary": "Delete an API key",
                    "parameters": [
                        {
                            "name": "api_key",
                            "in": "path",
                            "required": True,
                            "schema": {"type": "string"}
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "API key deleted successfully"
                        }
                    }
                }
            }
        },
        "components": {
            "securitySchemes": {
                "bearerAuth": {
                    "type": "http",
                    "scheme": "bearer",
                    "bearerFormat": "JWT"
                }
            }
        }
    }

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    try:
        # Check backend connectivity
        response = await make_backend_request("/health")
        backend_status = "healthy" if response.status_code == 200 else "unhealthy"
        
        return {
            "status": "healthy",
            "backend_status": backend_status,
            "backend_url": BACKEND_URL,
            "hf_token_configured": bool(HF_TOKEN),
            "timestamp": datetime.now().isoformat()
        }
    except Exception as e:
        return {
            "status": "unhealthy", 
            "error": str(e),
            "backend_url": BACKEND_URL,
            "hf_token_configured": bool(HF_TOKEN),
            "timestamp": datetime.now().isoformat()
        }


# ==================== CHAT COMPLETIONS ====================

@app.get("/models")
async def get_chat_models(token: str = Depends(verify_token)):
    """Get available chat models"""
    response = await make_backend_request("/models")
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail="Failed to fetch models")

@app.post("/chat/completions")
async def chat_completions(request: SimpleChatRequest, token: str = Depends(verify_token)):
    """Chat completions proxy (OpenAI Compatible)"""
    # Validate input - either messages or prompt must be provided
    if not request.messages and not request.prompt:
        raise HTTPException(status_code=400, detail="Either 'messages' or 'prompt' must be provided")
    
    # Convert request to dict and handle None values properly
    request_data = request.dict(exclude_none=True)
    
    response = await make_backend_request("/chat/completions", "POST", request_data)
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

# ==================== IMAGE GENERATION ====================

@app.post("/image/generate")
async def generate_image(request: GenerationRequest, token: str = Depends(verify_token)):
    """Image generation proxy"""
    response = await make_backend_request("/image/generate", "POST", request.dict())
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

# ==================== WEB SEARCH ====================

@app.post("/web/search")
async def web_search(request: SearchRequest, token: str = Depends(verify_token)):
    """Web search proxy"""
    response = await make_backend_request("/web/search", "POST", request.dict())
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

@app.post("/image/search") 
async def image_search(request: SearchRequest, token: str = Depends(verify_token)):
    """Image search proxy"""
    response = await make_backend_request("/image/search", "POST", request.dict())
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

@app.post("/videos/search")
async def video_search(request: SearchRequest, token: str = Depends(verify_token)):
    """Video search proxy"""
    response = await make_backend_request("/videos/search", "POST", request.dict())
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

# ==================== TEXT-TO-SPEECH ====================

@app.get("/tts/{provider}/voices")
async def get_tts_voices(provider: str, token: str = Depends(verify_token)):
    """Get TTS voices for provider"""
    response = await make_backend_request(f"/tts/{provider}/voices")
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

@app.post("/tts/generate")
async def generate_tts(request: TTSRequest, token: str = Depends(verify_token)):
    """Generate TTS audio"""
    response = await make_backend_request("/tts/generate", "POST", request.dict())
    if response.status_code == 200:
        return response.json()
    else:
        raise HTTPException(status_code=response.status_code, detail=response.text)

@app.get("/audio/{audio_id}")
async def serve_audio(audio_id: str, token: str = Depends(verify_token)):
    """
    Proxy audio file serving
    
    To access audio files, use: https://at41rv-a77.hf.space/v1/audio/{audio_id}
    Example: https://at41rv-a77.hf.space/v1/audio/GesseritTTS_Emma_1750428123_abc12345
    """
    try:
        response = await make_backend_request(f"/audio/{audio_id}")
        if response.status_code == 200:
            return StreamingResponse(
                iter([response.content]),
                media_type="audio/mpeg",
                headers={"Content-Disposition": f"inline; filename={audio_id}.mp3"}
            )
        else:
            raise HTTPException(status_code=response.status_code, detail="Audio file not found")
    except Exception as e:
        logger.error(f"Audio serving error: {str(e)}")
        raise HTTPException(status_code=404, detail="Audio file not found")

@app.get("/image/{image_id}")
async def serve_image(image_id: str, token: str = Depends(verify_token)):
    """
    Proxy image file serving
    
    To access image files, use: https://at41rv-a77.hf.space/v1/image/{image_id}
    Example: https://at41rv-a77.hf.space/v1/image/img_1750428123_abc12345
    """
    try:
        response = await make_backend_request(f"/image/{image_id}")
        if response.status_code == 200:
            return StreamingResponse(
                iter([response.content]),
                media_type="image/jpeg",
                headers={"Content-Disposition": f"inline; filename={image_id}.jpg"}
            )
        else:
            raise HTTPException(status_code=response.status_code, detail="Image file not found")
    except Exception as e:
        logger.error(f"Image serving error: {str(e)}")
        raise HTTPException(status_code=404, detail="Image file not found")

@app.post("/transcribe")
async def transcribe_audio(audio_file: UploadFile = File(...), token: str = Depends(verify_token)):
    """Audio transcription proxy"""
    try:
        logger.info(f"Proxy: Received transcription request for file: {audio_file.filename}")
        logger.info(f"Proxy: Content type: {audio_file.content_type}")
        
        # Read file content
        file_content = await audio_file.read()
        logger.info(f"Proxy: File size: {len(file_content)} bytes")
        
        if len(file_content) == 0:
            return {
                "success": False,
                "message": "Empty file uploaded",
                "transcription": None,
                "filename": audio_file.filename,
                "file_size": 0
            }
        
        # Check file size (limit to 50MB)
        max_size = 50 * 1024 * 1024  # 50MB
        if len(file_content) > max_size:
            return {
                "success": False,
                "message": "File too large. Maximum size is 50MB",
                "transcription": None,
                "filename": audio_file.filename,
                "file_size": len(file_content)
            }
        
        # Reset file pointer for forwarding
        await audio_file.seek(0)
        
        # Prepare file for backend request
        files = {
            "audio_file": (audio_file.filename or "audio.mp3", await audio_file.read(), audio_file.content_type or "audio/mpeg")
        }
        
        logger.info(f"Proxy: Forwarding request to backend...")
        
        # Use longer timeout for transcription
        response = await make_backend_request("/transcribe", "POST", files=files, timeout=120.0)
        
        logger.info(f"Proxy: Backend responded with status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            logger.info("Proxy: Successfully received transcription from backend")
            return result
        else:
            logger.error(f"Proxy: Backend error: {response.text}")
            return {
                "success": False,
                "message": f"Backend error: {response.status_code}",
                "transcription": None,
                "filename": audio_file.filename,
                "file_size": len(file_content)
            }
            
    except Exception as e:
        logger.error(f"Proxy: Transcription error: {str(e)}")
        return {
            "success": False,
            "message": f"Proxy error: {str(e)}",
            "transcription": None,
            "filename": audio_file.filename if audio_file else None,
            "file_size": None
        }

# ==================== GENERIC PROXY ====================

# Generic proxy endpoints removed for better security and control

# ==================== API KEY MANAGEMENT ====================

def get_user_id_from_request(request) -> str:
    """Generate a user ID from request (using IP address as identifier)"""
    # In a real application, you might use session tokens, user authentication, etc.
    # For now, we'll use IP address as a simple identifier
    client_ip = getattr(request.client, 'host', 'unknown')
    return f"user_{client_ip}"

@app.post("/generate-api-key", response_model=APIKeyResponse)
async def create_api_key(request: APIKeyCreateRequest, http_request: Request):
    """
    Generate a new named API key for accessing the OMNIAPI services
    
    This endpoint creates a permanent API key with a custom name that starts with 'oa' 
    and can be used to authenticate with all API endpoints. Each user can create up to 1 API key.
    
    - **name**: Custom name for your API key (1-50 characters)
    
    Returns:
    - **api_key**: Your new API key (starts with 'oa')
    - **name**: The name you assigned to this key
    - **usage_note**: Instructions on how to use the API key
    
    Usage:
    Include the API key in the Authorization header as: `Bearer your_api_key_here`
    """
    try:
        # Get user ID from request
        user_id = get_user_id_from_request(http_request)
        
        # Forward request to backend with user tracking
        request_data = {"name": request.name, "user_id": user_id}
        response = await make_backend_request("/generate-api-key", "POST", request_data)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise HTTPException(status_code=response.status_code, detail=response.text)
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500, 
            detail=f"Failed to generate API key: {str(e)}"
        )

@app.get("/api-keys/list", response_model=UserAPIKeysResponse)
async def list_user_api_keys(http_request: Request, token: str = Depends(verify_token)):
    """
    List all API keys for the current authenticated user
    
    This endpoint shows all API keys created by the current user, including:
    - Key name and masked API key (for security)
    - Creation date
    - Last used date
    - Usage count
    
    Requires authentication - users can only view their own keys
    """
    try:
        logger.info(f"Proxy: Authenticated API key list request")
        
        # Forward the authenticated request to backend
        headers = {
            "Authorization": f"Bearer {token}",
            "User-Agent": "OMNIAPI-Proxy/1.0",
            "Content-Type": "application/json"
        }
        
        async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
            response = await client.get(
                f"{BACKEND_URL}/api-keys/list",
                headers=headers
            )
        
        logger.info(f"Proxy: Backend responded with status {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            logger.info(f"Proxy: Found {result.get('total_keys', 0)} API keys for authenticated user")
            return result
        else:
            logger.error(f"Proxy: Backend error: {response.text}")
            try:
                error_data = response.json()
                detail = error_data.get("detail", response.text)
            except:
                detail = response.text
            raise HTTPException(status_code=response.status_code, detail=detail)
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Proxy: Failed to list API keys: {str(e)}")
        raise HTTPException(
            status_code=500, 
            detail=f"Failed to list API keys: {str(e)}"
        )

@app.delete("/api-keys/{api_key}", response_model=APIKeyDeleteResponse)
async def delete_user_api_key(api_key: str, http_request: Request, token: str = Depends(verify_token)):
    """
    Delete a specific API key
    
    This endpoint allows users to delete their own API keys.
    Only the user who created the key can delete it.
    
    - **api_key**: The full API key to delete
    """
    try:
        user_id = get_user_id_from_request(http_request)
        logger.info(f"Proxy: Delete request for API key {api_key[:10]}... from user {user_id}")
        
        # Forward the authenticated user's token to the backend
        headers = {
            "Authorization": f"Bearer {token}",
            "User-Agent": "OMNIAPI-Proxy/1.0",
            "Content-Type": "application/json"
        }
        
        async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
            response = await client.delete(
                f"{BACKEND_URL}/api-keys/{api_key}",
                headers=headers
            )
        
        logger.info(f"Proxy: Backend responded with status {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            logger.info("Proxy: API key deleted successfully")
            return result
        else:
            logger.error(f"Proxy: Backend error: {response.text}")
            # Try to parse the error response
            try:
                error_data = response.json()
                detail = error_data.get("detail", response.text)
            except:
                detail = response.text
            raise HTTPException(status_code=response.status_code, detail=detail)
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Proxy: Failed to delete API key: {str(e)}")
        raise HTTPException(
            status_code=500, 
            detail=f"Failed to delete API key: {str(e)}"
        )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7862)