File size: 31,466 Bytes
8800c81
 
 
 
 
 
 
664a5eb
 
8800c81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a42236e
 
 
 
 
 
664a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import logging
import re
import urllib.error
import urllib.request
from typing import Any

import httpx

from gdrive_sync import get_secret

logger = logging.getLogger("ai_provider")
logger.setLevel(logging.INFO)

# Optional genai import
try:
    from google import genai
    from google.genai import types
except ImportError:
    genai = None
    types = None


def clean_json_response(raw_text: str) -> str:
    """Strips markdown code blocks, comments, or leading/trailing text to extract clean JSON."""
    if not raw_text:
        return ""
    text = raw_text.strip()

    # Remove markdown code fences if present
    match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text, re.IGNORECASE)
    if match:
        text = match.group(1).strip()

    # If text is still wrapped in another fence or has leading text
    if not (text.startswith("{") or text.startswith("[")):
        start_brace = text.find("{")
        start_bracket = text.find("[")
        if start_brace != -1 and (start_bracket == -1 or start_brace < start_bracket):
            end_brace = text.rfind("}")
            if end_brace != -1:
                text = text[start_brace : end_brace + 1]
        elif start_bracket != -1:
            end_bracket = text.rfind("]")
            if end_bracket != -1:
                text = text[start_bracket : end_bracket + 1]

    return text.strip()


def call_gemini(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls Google Gemini API with fallback models."""
    models = [
        "gemini-3.5-flash-lite",
        "gemini-2.5-flash",
        "gemini-3.7-flash",
        "gemini-2.5-flash-lite",
        "gemini-3.5-flash",
        "gemini-2.5-pro",
        "gemini-2.0-flash",
        "gemini-1.5-flash",
    ]

    # If official SDK is available
    if genai is not None:
        client = genai.Client(api_key=api_key)
        last_err = None
        for model_name in models:
            try:
                config = (
                    types.GenerateContentConfig(
                        system_instruction=system_instruction,
                        response_mime_type="application/json",
                    )
                    if is_json
                    else types.GenerateContentConfig(
                        system_instruction=system_instruction,
                    )
                )
                response = client.models.generate_content(
                    model=model_name, contents=user_prompt, config=config
                )
                if response and hasattr(response, "text") and response.text:
                    return response.text
            except Exception as e:
                last_err = e
                logger.warning(f"Gemini model {model_name} failed: {e}")
                continue
        if last_err:
            raise last_err
        raise RuntimeError("Gemini failed to return text")

    # Fallback to direct REST call if SDK missing
    last_err = None
    for model_name in models:
        try:
            url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
            payload = {
                "contents": [{"parts": [{"text": user_prompt}]}],
                "systemInstruction": {"parts": [{"text": system_instruction}]},
            }
            if is_json:
                payload["generationConfig"] = {"responseMimeType": "application/json"}

            req = urllib.request.Request(
                url,
                data=json.dumps(payload).encode("utf-8"),
                headers={"Content-Type": "application/json"},
            )
            with urllib.request.urlopen(req, timeout=30) as resp:
                data = json.loads(resp.read().decode("utf-8"))
                candidates = data.get("candidates", [])
                if candidates:
                    parts = candidates[0].get("content", {}).get("parts", [])
                    if parts:
                        return parts[0].get("text", "")
        except Exception as e:
            last_err = e
            continue
    if last_err:
        raise last_err
    raise RuntimeError("Gemini REST API failed")


def stream_gemini(api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False):
    """Streams Google Gemini API responses chunk by chunk."""
    models = [
        "gemini-2.5-flash",
        "gemini-3.5-flash-lite",
        "gemini-3.7-flash",
        "gemini-2.5-flash-lite",
        "gemini-3.5-flash",
        "gemini-2.0-flash",
        "gemini-1.5-flash",
    ]
    if genai is not None:
        client = genai.Client(api_key=api_key)
        for model_name in models:
            try:
                config = (
                    types.GenerateContentConfig(
                        system_instruction=system_instruction,
                        response_mime_type="application/json",
                    )
                    if is_json
                    else types.GenerateContentConfig(
                        system_instruction=system_instruction,
                    )
                )
                response = client.models.generate_content_stream(
                    model=model_name, contents=user_prompt, config=config
                )
                has_yielded = False
                for chunk in response:
                    if chunk and hasattr(chunk, "text") and chunk.text:
                        has_yielded = True
                        yield chunk.text
                if has_yielded:
                    return
            except Exception as e:
                logger.warning(f"Gemini streaming model {model_name} failed: {e}")
                continue

    # Fallback to standard call if streaming fails or SDK missing
    full_text = call_gemini(api_key, system_instruction, user_prompt, is_json=is_json)
    if full_text:
        yield full_text


def call_groq(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls Groq Cloud API with OpenAI-compatible payload."""
    models = [
        "qwen/qwen3.8-27b",
        "openai/gpt-oss-20b",
        "qwen/qwen3.6-27b",
        "openai/gpt-oss-120b",
        "groq/compound-mini",
        "groq/compound",
    ]
    url = "https://api.groq.com/openai/v1/chat/completions"
    last_err = None

    for model_name in models:
        try:
            payload: dict[str, Any] = {
                "model": model_name,
                "messages": [
                    {"role": "system", "content": system_instruction},
                    {"role": "user", "content": user_prompt},
                ],
                "temperature": 0.2,
            }
            if is_json:
                payload["response_format"] = {"type": "json_object"}

            req = urllib.request.Request(
                url,
                data=json.dumps(payload).encode("utf-8"),
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {api_key}",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
                },
            )
            with urllib.request.urlopen(req, timeout=30) as resp:
                data = json.loads(resp.read().decode("utf-8"))
                choices = data.get("choices", [])
                if choices:
                    content = choices[0].get("message", {}).get("content", "")
                    if content:
                        return content
        except Exception as e:
            last_err = e
            logger.warning(f"Groq model {model_name} failed: {e}")
            continue

    if last_err:
        raise last_err
    raise RuntimeError("Groq failed to return content")


def call_openrouter(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls OpenRouter API with free and standard model fallbacks."""
    models = [
        "openrouter/free",
        "deepseek/deepseek-chat",
        "meta-llama/llama-3.3-70b-instruct",
        "minimax/minimax-m2.7:free",
        "google/gemma-4-31b-it:free",
        "meta-llama/llama-3.1-8b-instruct:free",
    ]
    url = "https://openrouter.ai/api/v1/chat/completions"
    last_err = None

    for model_name in models:
        try:
            payload: dict[str, Any] = {
                "model": model_name,
                "messages": [
                    {"role": "system", "content": system_instruction},
                    {"role": "user", "content": user_prompt},
                ],
                "temperature": 0.2,
            }
            if is_json:
                payload["response_format"] = {"type": "json_object"}

            req = urllib.request.Request(
                url,
                data=json.dumps(payload).encode("utf-8"),
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {api_key}",
                    "HTTP-Referer": "https://algospaced.io",
                    "X-Title": "AlgoSpaced DSA",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
                },
            )
            with urllib.request.urlopen(req, timeout=30) as resp:
                data = json.loads(resp.read().decode("utf-8"))
                choices = data.get("choices", [])
                if choices:
                    content = choices[0].get("message", {}).get("content", "")
                    if content:
                        return content
        except Exception as e:
            last_err = e
            logger.warning(f"OpenRouter model {model_name} failed: {e}")
            continue

    if last_err:
        raise last_err
    raise RuntimeError("OpenRouter failed to return content")


def detect_provider(provider: str | None, api_key: str | None) -> str:
    """Infers provider from name or key pattern."""
    if provider:
        p = provider.lower().strip()
        if "groq" in p:
            return "groq"
        if "openrouter" in p or "open_router" in p:
            return "openrouter"
        if "gemini" in p or "google" in p:
            return "gemini"

    if api_key:
        k = api_key.strip()
        if k.startswith("gsk_"):
            return "groq"
        if k.startswith("sk-or-"):
            return "openrouter"
        if k.startswith("AIza"):
            return "gemini"

    return "gemini"


def generate_ai_content(
    system_instruction: str,
    user_prompt: str,
    is_json: bool = False,
    custom_provider: str | None = None,
    custom_api_key: str | None = None,
) -> tuple[str, str]:
    """
    Unified multi-provider AI dispatcher with automatic failover.
    Returns tuple of (response_text, provider_used).
    """
    # 1. Custom BYOK Request
    if custom_api_key and custom_api_key.strip():
        key = custom_api_key.strip()
        provider = detect_provider(custom_provider, key)
        if provider == "groq":
            text = call_groq(key, system_instruction, user_prompt, is_json=is_json)
            return text, "groq (custom)"
        elif provider == "openrouter":
            text = call_openrouter(key, system_instruction, user_prompt, is_json=is_json)
            return text, "openrouter (custom)"
        else:
            text = call_gemini(key, system_instruction, user_prompt, is_json=is_json)
            return text, "gemini (custom)"

    # 2. Server Shared Default Tier (Multi-Provider Fallback Chain)
    gemini_key = get_secret("GEMINI_API_KEY")
    groq_key = get_secret("GROQ_API_KEY")
    openrouter_key = get_secret("OPENROUTER_API_KEY")

    errors: list[str] = []

    # Priority 1: Gemini
    if gemini_key:
        try:
            text = call_gemini(gemini_key, system_instruction, user_prompt, is_json=is_json)
            return text, "gemini (server)"
        except Exception as e:
            err_msg = f"Gemini server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    # Priority 2: Groq (if available on server)
    if groq_key:
        try:
            text = call_groq(groq_key, system_instruction, user_prompt, is_json=is_json)
            return text, "groq (server fallback)"
        except Exception as e:
            err_msg = f"Groq server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    # Priority 3: OpenRouter (if available on server)
    if openrouter_key:
        try:
            text = call_openrouter(openrouter_key, system_instruction, user_prompt, is_json=is_json)
            return text, "openrouter (server fallback)"
        except Exception as e:
            err_msg = f"OpenRouter server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    if not (gemini_key or groq_key or openrouter_key):
        raise RuntimeError(
            "No AI API keys configured on server. Please configure your API key in Settings."
        )

    raise RuntimeError(f"All AI providers failed. Summary of errors: {'; '.join(errors)}")


def stream_ai_content(
    system_instruction: str,
    user_prompt: str,
    is_json: bool = False,
    custom_provider: str | None = None,
    custom_api_key: str | None = None,
):
    """
    Streams AI content chunks. Yields tuples of (chunk_text, provider_name).
    """
    # 1. Custom BYOK Request
    if custom_api_key and custom_api_key.strip():
        key = custom_api_key.strip()
        provider = detect_provider(custom_provider, key)
        if provider == "gemini":
            for chunk in stream_gemini(key, system_instruction, user_prompt, is_json=is_json):
                yield chunk, "gemini (custom)"
            return
        elif provider == "groq":
            text = call_groq(key, system_instruction, user_prompt, is_json=is_json)
            yield text, "groq (custom)"
            return
        elif provider == "openrouter":
            text = call_openrouter(key, system_instruction, user_prompt, is_json=is_json)
            yield text, "openrouter (custom)"
            return
        else:
            for chunk in stream_gemini(key, system_instruction, user_prompt, is_json=is_json):
                yield chunk, "gemini (custom)"
            return

    # 2. Server Shared Default Tier
    gemini_key = get_secret("GEMINI_API_KEY")
    if gemini_key:
        try:
            for chunk in stream_gemini(
                gemini_key, system_instruction, user_prompt, is_json=is_json
            ):
                yield chunk, "gemini (server)"
            return
        except Exception as e:
            logger.warning(f"Gemini server stream failed: {e}")

    # Fallback to standard generation
    text, provider = generate_ai_content(
        system_instruction=system_instruction,
        user_prompt=user_prompt,
        is_json=is_json,
        custom_provider=custom_provider,
        custom_api_key=custom_api_key,
    )
    yield text, provider


def generate_text(
    prompt: str,
    custom_api_key: str | None = None,
    custom_provider: str | None = None,
) -> dict[str, Any]:
    """Helper for single-prompt text generation."""
    try:
        text, provider = generate_ai_content(
            system_instruction="You are an expert programming assistant.",
            user_prompt=prompt,
            is_json=False,
            custom_provider=custom_provider,
            custom_api_key=custom_api_key,
        )
        return {"text": text, "provider": provider}
    except Exception as e:
        logger.error(f"Error in generate_text: {e}")
        return {"text": "", "error": str(e)}


async def generate_text_async(
    prompt: str,
    custom_api_key: str | None = None,
    custom_provider: str | None = None,
) -> dict[str, Any]:
    """Helper for async single-prompt text generation."""
    try:
        text, provider = await generate_ai_content_async(
            system_instruction="You are an expert programming assistant.",
            user_prompt=prompt,
            is_json=False,
            custom_provider=custom_provider,
            custom_api_key=custom_api_key,
        )
        return {"text": text, "provider": provider}
    except Exception as e:
        logger.error(f"Error in generate_text_async: {e}")
        return {"text": "", "error": str(e)}


async def call_gemini_async(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls Google Gemini API asynchronously with fallback models."""
    models = [
        "gemini-3.5-flash-lite",
        "gemini-2.5-flash",
        "gemini-3.7-flash",
        "gemini-2.5-flash-lite",
        "gemini-3.5-flash",
        "gemini-2.5-pro",
        "gemini-2.0-flash",
        "gemini-1.5-flash",
    ]

    # If official SDK is available
    if genai is not None:
        client = genai.Client(api_key=api_key)
        last_err = None
        for model_name in models:
            try:
                config = (
                    types.GenerateContentConfig(
                        system_instruction=system_instruction,
                        response_mime_type="application/json",
                    )
                    if is_json
                    else types.GenerateContentConfig(
                        system_instruction=system_instruction,
                    )
                )
                response = await client.aio.models.generate_content(
                    model=model_name, contents=user_prompt, config=config
                )
                if response and hasattr(response, "text") and response.text:
                    return response.text
            except Exception as e:
                last_err = e
                logger.warning(f"Gemini async model {model_name} failed: {e}")
                continue
        if last_err:
            raise last_err
        raise RuntimeError("Gemini failed to return text")

    # Fallback to direct REST call via httpx if SDK missing
    last_err = None
    async with httpx.AsyncClient(timeout=30.0) as http_client:
        for model_name in models:
            try:
                url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
                payload = {
                    "contents": [{"parts": [{"text": user_prompt}]}],
                    "systemInstruction": {"parts": [{"text": system_instruction}]},
                }
                if is_json:
                    payload["generationConfig"] = {"responseMimeType": "application/json"}

                resp = await http_client.post(
                    url, json=payload, headers={"Content-Type": "application/json"}
                )
                if resp.status_code == 200:
                    data = resp.json()
                    candidates = data.get("candidates", [])
                    if candidates:
                        parts = candidates[0].get("content", {}).get("parts", [])
                        if parts:
                            return parts[0].get("text", "")
                else:
                    err_text = resp.text[:300]
                    last_err = RuntimeError(
                        f"Gemini {model_name} HTTP {resp.status_code}: {err_text}"
                    )
                    logger.warning(
                        f"Gemini async REST model {model_name} returned {resp.status_code}: {err_text}"
                    )
            except Exception as e:
                last_err = e
                continue
    if last_err:
        raise last_err
    raise RuntimeError("Gemini REST API failed")


async def stream_gemini_async(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
):
    """Streams Google Gemini API responses chunk by chunk asynchronously."""
    models = [
        "gemini-2.5-flash",
        "gemini-3.5-flash-lite",
        "gemini-3.7-flash",
        "gemini-2.5-flash-lite",
        "gemini-3.5-flash",
        "gemini-2.0-flash",
        "gemini-1.5-flash",
    ]
    if genai is not None:
        client = genai.Client(api_key=api_key)
        for model_name in models:
            has_yielded = False
            try:
                config = (
                    types.GenerateContentConfig(
                        system_instruction=system_instruction,
                        response_mime_type="application/json",
                    )
                    if is_json
                    else types.GenerateContentConfig(
                        system_instruction=system_instruction,
                    )
                )
                response = await client.aio.models.generate_content_stream(
                    model=model_name, contents=user_prompt, config=config
                )
                async for chunk in response:
                    if chunk and hasattr(chunk, "text") and chunk.text:
                        has_yielded = True
                        yield chunk.text
                if has_yielded:
                    return
            except Exception as e:
                logger.warning(f"Gemini async streaming model {model_name} failed: {e}")
                if has_yielded:
                    # Stream has already partially sent data to client; do not duplicate
                    return
                continue

    # Fallback to standard async call if streaming fails or SDK missing
    full_text = await call_gemini_async(api_key, system_instruction, user_prompt, is_json=is_json)
    if full_text:
        yield full_text


async def call_groq_async(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls Groq Cloud API asynchronously."""
    models = [
        "qwen/qwen3.8-27b",
        "openai/gpt-oss-20b",
        "qwen/qwen3.6-27b",
        "openai/gpt-oss-120b",
        "groq/compound-mini",
        "groq/compound",
    ]
    url = "https://api.groq.com/openai/v1/chat/completions"
    last_err = None

    async with httpx.AsyncClient(timeout=30.0) as http_client:
        for model_name in models:
            try:
                payload: dict[str, Any] = {
                    "model": model_name,
                    "messages": [
                        {"role": "system", "content": system_instruction},
                        {"role": "user", "content": user_prompt},
                    ],
                    "temperature": 0.2,
                }
                if is_json:
                    payload["response_format"] = {"type": "json_object"}

                headers = {
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {api_key}",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
                }
                resp = await http_client.post(url, json=payload, headers=headers)
                if resp.status_code == 200:
                    data = resp.json()
                    choices = data.get("choices", [])
                    if choices:
                        content = choices[0].get("message", {}).get("content", "")
                        if content:
                            return content
                else:
                    err_text = resp.text[:300]
                    last_err = RuntimeError(
                        f"Groq {model_name} HTTP {resp.status_code}: {err_text}"
                    )
                    logger.warning(
                        f"Groq async model {model_name} returned {resp.status_code}: {err_text}"
                    )
            except Exception as e:
                last_err = e
                logger.warning(f"Groq async model {model_name} failed: {e}")
                continue

    if last_err:
        raise last_err
    raise RuntimeError("Groq failed to return content")


async def call_openrouter_async(
    api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
    """Calls OpenRouter API asynchronously."""
    models = [
        "openrouter/free",
        "deepseek/deepseek-chat",
        "meta-llama/llama-3.3-70b-instruct",
        "minimax/minimax-m2.7:free",
        "google/gemma-4-31b-it:free",
        "meta-llama/llama-3.1-8b-instruct:free",
    ]
    url = "https://openrouter.ai/api/v1/chat/completions"
    last_err = None

    async with httpx.AsyncClient(timeout=30.0) as http_client:
        for model_name in models:
            try:
                payload: dict[str, Any] = {
                    "model": model_name,
                    "messages": [
                        {"role": "system", "content": system_instruction},
                        {"role": "user", "content": user_prompt},
                    ],
                    "temperature": 0.2,
                }
                if is_json:
                    payload["response_format"] = {"type": "json_object"}

                headers = {
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {api_key}",
                    "HTTP-Referer": "https://algospaced.io",
                    "X-Title": "AlgoSpaced DSA",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
                }
                resp = await http_client.post(url, json=payload, headers=headers)
                if resp.status_code == 200:
                    data = resp.json()
                    choices = data.get("choices", [])
                    if choices:
                        content = choices[0].get("message", {}).get("content", "")
                        if content:
                            return content
                else:
                    err_text = resp.text[:300]
                    last_err = RuntimeError(
                        f"OpenRouter {model_name} HTTP {resp.status_code}: {err_text}"
                    )
                    logger.warning(
                        f"OpenRouter async model {model_name} returned {resp.status_code}: {err_text}"
                    )
            except Exception as e:
                last_err = e
                logger.warning(f"OpenRouter async model {model_name} failed: {e}")
                continue

    if last_err:
        raise last_err
    raise RuntimeError("OpenRouter failed to return content")


async def generate_ai_content_async(
    system_instruction: str,
    user_prompt: str,
    is_json: bool = False,
    custom_provider: str | None = None,
    custom_api_key: str | None = None,
) -> tuple[str, str]:
    """
    Unified multi-provider AI dispatcher with automatic failover (async).
    Returns tuple of (response_text, provider_used).
    """
    # 1. Custom BYOK Request
    if custom_api_key and custom_api_key.strip():
        key = custom_api_key.strip()
        provider = detect_provider(custom_provider, key)
        if provider == "groq":
            text = await call_groq_async(key, system_instruction, user_prompt, is_json=is_json)
            return text, "groq (custom)"
        elif provider == "openrouter":
            text = await call_openrouter_async(
                key, system_instruction, user_prompt, is_json=is_json
            )
            return text, "openrouter (custom)"
        else:
            text = await call_gemini_async(key, system_instruction, user_prompt, is_json=is_json)
            return text, "gemini (custom)"

    # 2. Server Shared Default Tier (Multi-Provider Fallback Chain)
    gemini_key = get_secret("GEMINI_API_KEY")
    groq_key = get_secret("GROQ_API_KEY")
    openrouter_key = get_secret("OPENROUTER_API_KEY")

    errors: list[str] = []

    # Priority 1: Gemini
    if gemini_key:
        try:
            text = await call_gemini_async(
                gemini_key, system_instruction, user_prompt, is_json=is_json
            )
            return text, "gemini (server)"
        except Exception as e:
            err_msg = f"Gemini server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    # Priority 2: Groq (if available on server)
    if groq_key:
        try:
            text = await call_groq_async(groq_key, system_instruction, user_prompt, is_json=is_json)
            return text, "groq (server fallback)"
        except Exception as e:
            err_msg = f"Groq server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    # Priority 3: OpenRouter (if available on server)
    if openrouter_key:
        try:
            text = await call_openrouter_async(
                openrouter_key, system_instruction, user_prompt, is_json=is_json
            )
            return text, "openrouter (server fallback)"
        except Exception as e:
            err_msg = f"OpenRouter server key failed: {e}"
            logger.warning(err_msg)
            errors.append(err_msg)

    if not (gemini_key or groq_key or openrouter_key):
        raise RuntimeError(
            "No AI API keys configured on server. Please configure your API key in Settings."
        )

    raise RuntimeError(f"All AI providers failed. Summary of errors: {'; '.join(errors)}")


async def stream_ai_content_async(
    system_instruction: str,
    user_prompt: str,
    is_json: bool = False,
    custom_provider: str | None = None,
    custom_api_key: str | None = None,
):
    """
    Streams AI content chunks asynchronously. Yields tuples of (chunk_text, provider_name).
    """
    # 1. Custom BYOK Request
    if custom_api_key and custom_api_key.strip():
        key = custom_api_key.strip()
        provider = detect_provider(custom_provider, key)
        if provider == "gemini":
            async for chunk in stream_gemini_async(
                key, system_instruction, user_prompt, is_json=is_json
            ):
                yield chunk, "gemini (custom)"
            return
        elif provider == "groq":
            text = await call_groq_async(key, system_instruction, user_prompt, is_json=is_json)
            yield text, "groq (custom)"
            return
        elif provider == "openrouter":
            text = await call_openrouter_async(
                key, system_instruction, user_prompt, is_json=is_json
            )
            yield text, "openrouter (custom)"
            return
        else:
            async for chunk in stream_gemini_async(
                key, system_instruction, user_prompt, is_json=is_json
            ):
                yield chunk, "gemini (custom)"
            return

    # 2. Server Shared Default Tier
    gemini_key = get_secret("GEMINI_API_KEY")
    has_yielded_server = False
    if gemini_key:
        try:
            async for chunk in stream_gemini_async(
                gemini_key, system_instruction, user_prompt, is_json=is_json
            ):
                has_yielded_server = True
                yield chunk, "gemini (server)"
            return
        except Exception as e:
            logger.warning(f"Gemini server async stream failed: {e}")
            if has_yielded_server:
                return

    # Fallback to standard async generation
    text, provider = await generate_ai_content_async(
        system_instruction=system_instruction,
        user_prompt=user_prompt,
        is_json=is_json,
        custom_provider=custom_provider,
        custom_api_key=custom_api_key,
    )
    yield text, provider