File size: 34,479 Bytes
c49440d
 
 
 
 
 
 
 
 
 
 
 
3950291
c49440d
 
3950291
c49440d
 
 
3950291
c49440d
 
 
 
 
 
 
3950291
c49440d
 
3950291
 
 
 
 
 
 
 
 
 
13de702
c49440d
3950291
c49440d
 
 
3950291
 
 
c49440d
3950291
13de702
3950291
 
 
c49440d
3950291
 
 
c49440d
3950291
 
c49440d
 
 
 
 
 
 
3950291
c49440d
 
3950291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
3950291
 
c49440d
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13de702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175d0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13de702
 
c49440d
13de702
 
3950291
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
3950291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
55320cc
c49440d
 
55320cc
3950291
13de702
c49440d
 
 
13de702
c49440d
 
 
55320cc
3950291
13de702
 
 
 
 
 
 
 
3950291
13de702
 
 
 
 
 
 
c49440d
 
 
13de702
c49440d
 
 
3950291
 
55320cc
13de702
 
c49440d
 
 
13de702
55320cc
c49440d
 
 
 
 
 
 
 
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
13de702
 
3950291
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca03513
3950291
13de702
3950291
ca03513
c49440d
 
 
 
d3f3721
55320cc
d3f3721
55320cc
 
 
 
 
c49440d
d3f3721
 
55320cc
 
 
 
 
 
13de702
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
c49440d
 
55320cc
c49440d
 
3950291
55320cc
 
 
c49440d
3950291
55320cc
 
 
 
 
 
13de702
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49440d
55320cc
c49440d
 
 
 
 
 
 
 
 
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
import os
import re
import json
import time
import requests
from typing import List, Dict, Any, Optional
from dotenv import load_dotenv

load_dotenv()

from groq import Groq

# Supported frontier models across Cloudflare Workers AI and Groq (Curated: Qwen, DeepSeek R1, Gemma)
CLOUDFLARE_MODELS = {
    "Groq: Qwen 3.8 (27B Ultra Fast)": "groq:qwen/qwen3.8-27b",
    "Groq: Qwen 3.6 (27B High-Context)": "groq:qwen/qwen3.6-27b",
    "DeepSeek R1 (32B Frontier Reasoning)": "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
    "Gemma 4 (26B MoE Google Reasoning)": "@cf/google/gemma-4-26b-a4b-it",
    "Qwen 3.8 (27B Alibaba Frontier)": "@cf/qwen/qwen3.8-27b",
    "QwQ (32B Qwen Deep Logic)": "@cf/qwen/qwq-32b"
}

# System prompts structured specifically according to CA Foundation Business Laws marking scheme:
# - Case-Based Questions (CBQ): Provision -> Application -> Conclusion (Law -> Facts -> Result)
# - Theory / List Questions: Definition -> Section -> Headings & Essentials / Conditions -> Summary
# - General Conversational: Direct, concise, natural responses

CBQ_SYSTEM_PROMPT = """You are JurisAI, a legal study assistant designed, architected, and trained by Shashwat for CA Foundation Paper-2: Business Laws.
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SOURCE DISCIPLINE β€” BOOK EXCERPTS ARE YOUR ONLY AUTHORITY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Your ONLY source of legal content is the Official ICAI Book Excerpts provided below.
- EVERY section number, case law, legal rule, and provision you cite MUST appear in those excerpts.
- Do NOT introduce any legal principle, case name, section, or rule that is not explicitly written in the excerpts.
- Do NOT use your training data, general legal knowledge, or any external source to fill gaps.
- If a formula or calculation method is EXPLICITLY stated in the excerpts (e.g., "damages = market price βˆ’ contract price"), you MAY apply it to the given facts and show the working.
- If no formula or figure is stated in the excerpts, do NOT derive, compute, or guess any amount β€” instead state: "The specific amount is not mentioned in the provided ICAI study material excerpts."
- If the excerpts are insufficient to fully answer, say so clearly rather than supplementing from outside knowledge.

You are answering a **Practical / Case-Based Question (CBQ)**.
The CA Foundation answer structure is: **Provision β†’ Application β†’ Conclusion (Law β†’ Facts β†’ Result)**.

Structure your response using these exact markdown headers:

### πŸ›οΈ Conclusion / Direct Decision
State the outcome immediately and clearly (e.g., "B is entitled to..." or "The agreement is VOID").
Base this ONLY on what the retrieved excerpts establish.

### πŸ“‘ Provision β†’ Application β†’ Conclusion

**1. Provision / Legal Rule**
- Quote or closely paraphrase the governing Section(s) and Act EXACTLY as stated in the excerpts below.
- Do NOT cite any section or case law that does not appear in the excerpts.

**2. Application / Analysis**
- Apply the facts of the question to the legal rule drawn from the excerpts.
- Do NOT add rules, exceptions, or principles beyond what the excerpts contain.

**3. Final Conclusion**
- State the definitive result, grounded entirely in the excerpt content.

Official ICAI Book Excerpts:
----------------------------------------
{context_str}
----------------------------------------
"""

THEORY_SYSTEM_PROMPT = """You are JurisAI, a legal study assistant designed, architected, and trained by Shashwat for CA Foundation Paper-2: Business Laws.
When asked about your identity or creator, state that you are JurisAI, designed and trained by Shashwat.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SOURCE DISCIPLINE β€” BOOK EXCERPTS ARE YOUR ONLY AUTHORITY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Your ONLY source of legal content is the Official ICAI Book Excerpts provided below.
- EVERY definition, section number, case law, essential element, and example you state MUST come DIRECTLY from those excerpts.
- Do NOT use your training knowledge, general legal knowledge, or any external source to add content.
- Do NOT add, infer, or extrapolate ANY legal principle, case law, or statutory rule beyond what is explicitly written in the excerpts.
- If a formula or method is EXPLICITLY stated in the excerpts, you MAY apply it to the question's facts.
- If no formula or detail is given in the excerpts, say: "This detail is not covered in the provided ICAI study material excerpts."
- COMPLETENESS: When the question asks for a list (e.g., all grounds, all essentials, all exceptions), list EVERY item that appears in the excerpts β€” do NOT stop early or summarize prematurely.
- Ensure all markdown tables, lists, and sections are fully written and properly closed.

You are answering a **Theory / Descriptive Question**.
Structure your response using these markdown headers:

### πŸ›οΈ Definition & Governing Provision
- State the exact definition and section number as written in the excerpts.

### πŸ“‘ Detailed Explanation
- Use numbered lists for essentials, conditions, exceptions, or grounds β€” exactly as the book presents them.
- Include case laws ONLY if they appear in the excerpts, and state them exactly as presented.
- Use a markdown table when the book presents a comparative or tabular structure.

Official ICAI Book Excerpts:
----------------------------------------
{context_str}
----------------------------------------
"""

GENERAL_CHAT_SYSTEM_PROMPT = """You are JurisAI, a legal study assistant designed, architected, and trained by Shashwat for CA Foundation Business Laws.
When asked who created you, your origin, or your identity, clearly state that you are JurisAI, designed and trained by Shashwat.
Respond conversationally, concisely, and naturally to greetings, follow-ups, or general queries."""


class LegalRAGEngine:
    def __init__(self, retriever):
        self.retriever = retriever
        self._groq_key_index = 0

    def get_groq_keys(self) -> List[str]:
        keys = []

        def _add(val: Optional[str]):
            if not val:
                return
            for item in val.split(","):
                cleaned = item.strip()
                if cleaned and cleaned.startswith("gsk_") and cleaned not in keys:
                    keys.append(cleaned)

        # 1. HuggingFace Space secrets: gk1, gk2, gk3, ... gk50 (both lowercase and uppercase)
        for idx in range(1, 51):
            _add(os.getenv(f"gk{idx}"))
            _add(os.getenv(f"GK{idx}"))
            _add(os.getenv(f"gk_{idx}"))
            _add(os.getenv(f"GK_{idx}"))

        # 2. GROQ_API_KEYS (comma-separated list), GROQ_API_KEY
        _add(os.getenv("GROQ_API_KEYS"))
        _add(os.getenv("GROQ_API_KEY"))

        # 3. GROQ_API_KEY_1, GROQ_KEY_1 ...
        for idx in range(1, 51):
            _add(os.getenv(f"GROQ_API_KEY_{idx}"))
            _add(os.getenv(f"GROQ_KEY_{idx}"))

        # 4. Any generic environment variable with a valid gsk_ prefix
        for env_name, env_val in os.environ.items():
            if env_val.startswith("gsk_") and env_val not in keys:
                keys.append(env_val.strip())

        return keys

    def get_groq_clients_in_rotation(self) -> List[Groq]:
        keys = self.get_groq_keys()
        if not keys:
            return []
        # Rotate starting point so requests round-robin
        start_idx = self._groq_key_index % len(keys)
        self._groq_key_index += 1
        rotated_keys = keys[start_idx:] + keys[:start_idx]
        return [Groq(api_key=k) for k in rotated_keys]

    def format_context(self, retrieved_chunks: List[Dict[str, Any]]) -> str:
        formatted = []
        for i, chunk in enumerate(retrieved_chunks, 1):
            source_tag = f"[Excerpt {i}] Document: {chunk['title']} | Chapter: {chunk['chapter']} | Page: {chunk['page_number']}"
            formatted.append(f"{source_tag}\n{chunk['text']}\n")
        return "\n\n".join(formatted)

    def clean_output(self, raw_data: Any) -> Dict[str, str]:
        text = ""
        thinking_process = ""

        if isinstance(raw_data, dict):
            if "choices" in raw_data and len(raw_data["choices"]) > 0:
                choice = raw_data["choices"][0]
                msg = choice.get("message", {})
                text = msg.get("content", "") or ""
                thinking_process = msg.get("reasoning_content", "") or msg.get("reasoning", "") or ""
            elif "response" in raw_data:
                text = raw_data["response"]
            else:
                text = str(raw_data)
        else:
            text = str(raw_data)

        if "<think>" in text:
            think_match = re.search(r'<think>(.*?)</think>', text, flags=re.DOTALL)
            if think_match:
                if not thinking_process:
                    thinking_process = think_match.group(1).strip()
                text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
            elif "</think>" in text:
                parts = text.split("</think>", 1)
                if not thinking_process:
                    thinking_process = parts[0].replace("<think>", "").strip()
                text = parts[1].strip()

        return {
            "clean_answer": text.strip(),
            "thinking": thinking_process.strip()
        }

    def _call_cloudflare_chat(
        self,
        messages: List[Dict[str, str]],
        model_id: str,
        account_id: str,
        api_token: str
    ) -> Dict[str, str]:
        url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model_id}"
        headers = {
            "Authorization": f"Bearer {api_token}",
            "Content-Type": "application/json"
        }
        payload = {
            "messages": messages,
            "max_tokens": 2048,
            "temperature": 0.2
        }
        
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=60)
            data = resp.json()
            if not data.get("success"):
                errors = data.get("errors", [])
                return {"clean_answer": f"Cloudflare Workers AI Error: {errors}", "thinking": ""}
            
            res_payload = data.get("result", {})
            return self.clean_output(res_payload)
            
        except Exception as e:
            return {"clean_answer": f"Error connecting to Cloudflare Workers AI: {e}", "thinking": ""}

    def _normalize_legal_query(self, query: str) -> str:
        """Corrects common student typos in legal terminology to ensure high precision retrieval."""
        corrections = {
            r"\bvieel\b": "veil",
            r"\bviel\b": "veil",
            r"\bvail\b": "veil",
            r"\bcorparate\b": "corporate",
            r"\bcorporte\b": "corporate",
            r"\bpromisor\b": "promisor",
            r"\bpromiser\b": "promisor",
            r"\blibility\b": "liability",
            r"\bliabilty\b": "liability",
            r"\bseverel\b": "several",
            r"\bseverall\b": "several",
            r"\bagrement\b": "agreement",
            r"\bpartnr\b": "partner",
            r"\bpartneship\b": "partnership",
            r"\bconsideratn\b": "consideration",
            r"\bultra viers\b": "ultra vires",
            r"\bultravires\b": "ultra vires",
            r"\bcaveat emptre\b": "caveat emptor",
            r"\bminority\b": "minor",
            r"\bindeminty\b": "indemnity",
            r"\bgaurentee\b": "guarantee",
            r"\bgurantee\b": "guarantee",
            r"\bqusi\b": "quasi",
            r"\bnegociable\b": "negotiable",
            r"\bcheq\b": "cheque",
            r"\bcheck\b": "cheque",
            r"\bsole of goods\b": "sale of goods",
            r"\bcompnay\b": "company",
            r"\bcompnies\b": "companies"
        }
        normalized = query
        for pattern, replacement in corrections.items():
            normalized = re.sub(pattern, replacement, normalized, flags=re.IGNORECASE)
        return normalized

    def _enhance_search_query(self, query: str) -> str:
        """Uses fast instruction LLM to autonomously extract legal topics, acts, and sections without hardcoded lists."""
        clean_q = query.strip()
        if not clean_q:
            return query

        groq_clients = self.get_groq_clients_in_rotation()
        if not groq_clients:
            return query

        prompt = f"""You are an autonomous legal query analyzer for CA Foundation Paper-2: Business Laws (ICAI syllabus: Contract Act 1872, Sale of Goods Act 1930, Partnership Act 1932, LLP Act 2008, Companies Act 2013, Negotiable Instruments Act 1881).

Given this user question or case scenario, output ONLY 3 to 6 essential legal search terms (doctrine name, statutory concept, governing Act, and section numbers if applicable) to look up in the ICAI study material.
Do NOT explain anything. Return ONLY the search terms on a single line.

Question:
{clean_q}"""

        for client in groq_clients:
            try:
                resp = client.chat.completions.create(
                    model="qwen/qwen3.8-27b",
                    messages=[{"role": "user", "content": prompt}],
                    temperature=0.0,
                    max_tokens=35,
                    timeout=4.0
                )
                if resp and resp.choices and resp.choices[0].message:
                    extracted = resp.choices[0].message.content.strip()
                    # Strip quotes or markdown backticks if any
                    extracted = re.sub(r"[\"`\*]", "", extracted).replace("\n", " ").strip()
                    if extracted and len(extracted) > 3:
                        # For long case studies/story questions, the model-extracted statutory terms
                        # provide exact alignment with textbook chapter/section titles without noise.
                        if len(clean_q.split()) > 10:
                            return extracted
                        return f"{clean_q} {extracted}"
            except Exception as e:
                continue

        return query

    def decide_and_route(self, query: str, history: List[Dict[str, str]]) -> Dict[str, Any]:
        normalized_query = self._normalize_legal_query(query)
        q_lower = normalized_query.strip().lower().rstrip("?!.,")
        q_words = q_lower.split()

        # ── Conversational / social short phrases ───────────────────────────
        CASUAL_EXACT = {
            "hi", "hello", "hey", "howdy", "ok", "okay", "k", "yep", "yup",
            "yes", "no", "nope", "sure", "alright", "great", "nice", "cool",
            "thanks", "thank you", "ty", "thx", "thank u", "thank you so much",
            "ok thanks", "ok thank you", "ok thanku", "thanku", "ok ty",
            "good morning", "good afternoon", "good evening", "good night",
            "bye", "goodbye", "see you", "got it", "understood", "noted",
            "awesome", "perfect", "wonderful", "excellent", "good", "fine",
            "who are you", "what is your name", "who made you", "who created you",
            "who designed you", "who trained you", "what can you do", "help",
        }
        CASUAL_PREFIXES = (
            "who are you", "who made you", "who created you", "who designed you",
            "who trained you", "your name",
        )
        CASUAL_CONTAINS = (
            "thank", "thanks", "thanku", "thank u",
        )

        is_casual = (
            q_lower in CASUAL_EXACT
            or any(q_lower.startswith(p) for p in CASUAL_PREFIXES)
            or (len(q_words) <= 4 and any(w in q_lower for w in CASUAL_CONTAINS))
            or (len(q_words) <= 2 and q_lower in {"ok", "okay", "k", "sure", "alright",
                                                    "yep", "yup", "yes", "no", "nope",
                                                    "cool", "great", "nice", "good",
                                                    "got it", "noted", "fine", "awesome"})
        )

        if is_casual:
            return {
                "needs_rag": False,
                "question_type": "general",
                "search_query": "",
                "intent_reason": "General conversational query detected. Direct conversational response active."
            }

        # Case-based question patterns (Law -> Facts -> Result, Advise/Decide/Valid or Void)
        cbq_patterns = [
            "advise", "decide", "valid or void", "void or valid", "whether the agreement",
            "can mr", "can mrs", "can he", "can she", "is he liable", "is she liable",
            "is x liable", "is y liable", "is the firm liable", "state with reasons",
            "state reasons whether", "recovering the amount", "claim damages", "in the present case",
            "minor", "paridhee", "mittal", "rohan", "shyam", "rama", "buyer", "seller",
            "delivers", "delivered", "purchased", "sold to", "agreed to sell", "hire purchase",
            "auctioneer", "pledged", "third party", "promissory note"
        ]

        legal_keywords = [
            "act", "section", "partner", "firm", "contract", "company", "companies", "goods",
            "sale", "seller", "buyer", "bailment", "pledge", "agency", "agent", "consideration",
            "ultra vires", "guarantee", "indemnity", "quasi", "contingent", "promissory", "bill",
            "cheque", "negotiable", "minor", "void", "voidable", "moa", "aoa", "icai", "ca foundation",
            "paper 2", "memorandum", "articles", "unpaid", "lien", "stoppage", "dissolution",
            "holding out", "caveat emptor", "del credere", "sub-agent", "novatio", "remission",
            "wagering", "anticipatory", "appropriation", "finder of goods", "doctrine",
            "corporate veil", "lifting of", "piercing", "salomon", "separate legal entity",
            "perpetual succession", "common seal", "promoter", "shareholder", "director",
            "llp", "limited liability", "designated partner", "partner by holding out",
            "implied authority", "expulsion", "insolvent", "insolvency", "discharge",
            "breach", "damages", "quantum meruit", "performance", "joint", "several", "promisee"
        ]

        # Check for case study characteristics: facts/parties/problem scenario
        is_cbq = any(p in q_lower for p in cbq_patterns) or any(
            w in q_lower for w in ["mr.", "mrs.", "abc ltd", "xyz ltd", "a agrees", "b agrees", "x agrees", "y agrees"]
        )

        has_legal = any(kw in q_lower for kw in legal_keywords)
        prev_has_legal = False
        if history:
            last_msgs = " ".join([m.get("content", "") for m in history[-2:]]).lower()
            prev_has_legal = any(kw in last_msgs for kw in legal_keywords)

        # 1. CBQ classification
        if is_cbq and (has_legal or len(q_words) >= 4):
            enhanced_q = self._enhance_search_query(normalized_query)
            return {
                "needs_rag": True,
                "question_type": "cbq",
                "search_query": enhanced_q,
                "intent_reason": "Practical Case-Based Question (CBQ) identified. Applying Provision β†’ Application β†’ Conclusion (Law β†’ Facts β†’ Result) format."
            }

        # 2. Theory / Concept query
        if has_legal or len(q_words) >= 4:
            search_q = normalized_query
            followup_indicators = [
                "it", "its", "their", "that", "this", "above", "also", "exception", "exceptions",
                "what about", "rest", "remaining", "other", "others", "next", "more", "why", "where"
            ]
            is_followup = any(w in q_lower for w in followup_indicators)
            if is_followup and history:
                user_queries = [
                    m.get("content", "") for m in history
                    if m.get("role") == "user" and m.get("content", "").strip()
                ]
                if user_queries:
                    last_q = self._normalize_legal_query(user_queries[-1])
                    search_q = f"{last_q} {normalized_query}"

            enhanced_q = self._enhance_search_query(search_q)
            return {
                "needs_rag": True,
                "question_type": "theory",
                "search_query": enhanced_q,
                "intent_reason": "Theory / Syllabus Concept identified. Applying Definition β†’ Section β†’ Essential Conditions & Rules structure."
            }

        # 3. Short contextual follow-up (ONLY if query has some legal word linkage)
        if prev_has_legal and has_legal and len(q_words) <= 3:
            last_user_queries = [m.get("content", "") for m in history if m.get("role") == "user"]
            search_q = f"{self._normalize_legal_query(last_user_queries[-1])} {normalized_query}" if last_user_queries else normalized_query
            enhanced_q = self._enhance_search_query(search_q)
            return {
                "needs_rag": True,
                "question_type": "theory",
                "search_query": enhanced_q,
                "intent_reason": "Contextual follow-up to prior legal inquiry."
            }

        return {
            "needs_rag": False,
            "question_type": "general",
            "search_query": "",
            "intent_reason": "General conversational query. Direct conversational generation active."
        }


    def stream_answer_query(
        self,
        query: str,
        history: List[Dict[str, str]] = None,
        top_k: int = 5,
        chapter_filter: Optional[str] = None,
        model_name: Optional[str] = None
    ):
        if history is None:
            history = []

        cf_token = os.getenv("CLOUDFLARE_API_TOKEN")
        cf_acc_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
        model_id = model_name or os.getenv("CLOUDFLARE_MODEL")
        if not model_id or model_id == "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b":
            model_id = "groq:qwen/qwen3.8-27b"

        routing = self.decide_and_route(query, history)
        provider = "Groq" if (model_id.startswith("groq:") or not cf_token) else "Cloudflare"

        q_type = routing.get("question_type", "theory")
        intent_label = "General Direct Chat"
        if q_type == "cbq":
            intent_label = "Practical Case Study (CBQ)"
        elif q_type == "theory":
            intent_label = "Legal Theory & Syllabus"

        findings = {
            "intent": intent_label,
            "question_type": q_type,
            "intent_reason": routing["intent_reason"],
            "search_query": routing.get("search_query", ""),
            "chunks_found": 0,
            "top_sources": [],
            "model": model_id,
            "provider": provider
        }

        # Instant yield initial findings so UI immediately shows intent and progress
        yield f"event: findings\ndata: {json.dumps(findings)}\n\n"

        # Instant response for creator/identity questions to guarantee 0 latency and 100% accuracy
        q_norm = query.strip().lower().rstrip("?!., ")
        identity_triggers = [
            "who made you", "who created you", "who designed you", "who trained you",
            "who is your creator", "who built you", "who developed you", "who are you",
            "what is your name", "who's your creator", "whose model are you", "who made u",
            "who trained u", "tell me who made you"
        ]
        if any(trig in q_norm for trig in identity_triggers) or q_norm in ["who made you", "who are you", "who created you"]:
            creator_words = [
                "I ", "am ", "**JurisAI**, ", "an ", "autonomous ", "legal ", "intelligence ", "system ",
                "designed, ", "architected, ", "and ", "trained ", "by ", "**Shashwat** ", "specifically ",
                "for ", "CA ", "Foundation ", "Paper-2: ", "Business ", "Laws."
            ]
            for word in creator_words:
                yield f"event: token\ndata: {json.dumps({'text': word})}\n\n"
                time.sleep(0.025)
            yield f"event: usage\ndata: {json.dumps({'completion_tokens': len(creator_words)})}\n\n"
            yield "event: done\ndata: {}\n\n"
            return

        retrieved_chunks = []
        if routing["needs_rag"]:
            retrieved_chunks = self.retriever.retrieve(
                query=routing["search_query"] or query,
                top_k=top_k,
                chapter_filter=chapter_filter
            )
            findings["chunks_found"] = len(retrieved_chunks)
            findings["top_sources"] = [
                f"{c['title']} (Page {c['page_number']}) β€” Relevance: {c['retrieval_score']}"
                for c in retrieved_chunks[:3]
            ]
            # Yield updated findings with sources
            yield f"event: findings\ndata: {json.dumps(findings)}\n\n"

            context_str = self.format_context(retrieved_chunks)
            if q_type == "cbq":
                system_prompt = CBQ_SYSTEM_PROMPT.format(context_str=context_str)
            else:
                system_prompt = THEORY_SYSTEM_PROMPT.format(context_str=context_str)

            messages = [{"role": "system", "content": system_prompt}]
            for msg in history[-6:]:
                messages.append({"role": msg["role"], "content": msg["content"]})
            messages.append({"role": "user", "content": query})
        else:
            system_prompt = GENERAL_CHAT_SYSTEM_PROMPT
            messages = [{"role": "system", "content": system_prompt}]
            for msg in history[-8:]:
                messages.append({"role": msg["role"], "content": msg["content"]})
            messages.append({"role": "user", "content": query})

        groq_api_key = os.getenv("GROQ_API_KEY")

        # Stream via Groq if specified or as fallback
        if model_id.startswith("groq:") or not cf_token:
            clean_model = model_id.replace("groq:", "")
            # Ensure model passed to Groq is a valid Groq model name, not a Cloudflare @cf/ path
            valid_groq_models = ["qwen/qwen3.8-27b", "qwen/qwen3.6-27b", "llama-3.3-70b-versatile", "llama-3.1-8b-instant"]
            if clean_model.startswith("@cf/") or clean_model not in valid_groq_models:
                clean_model = "qwen/qwen3.8-27b"

            groq_clients = self.get_groq_clients_in_rotation()
            streamed = False
            last_err = None

            # Candidate models with high rate limit and reasoning power
            candidate_models = [clean_model]
            for m in ["qwen/qwen3.8-27b", "llama-3.3-70b-versatile", "qwen/qwen3.6-27b", "llama-3.1-8b-instant"]:
                if m not in candidate_models:
                    candidate_models.append(m)

            for g_model in candidate_models:
                if streamed:
                    break
                # Groq on-demand limits max output tokens per minute (OTPM) to 1000 on some tiers
                max_tokens = 1000
                for client in groq_clients:
                    try:
                        completion = client.chat.completions.create(
                            model=g_model,
                            messages=messages,
                            temperature=0.6,
                            max_completion_tokens=max_tokens,
                            top_p=0.95,
                            stream=True
                        )
                        total_tokens = 0
                        for chunk in completion:
                            token = chunk.choices[0].delta.content or ""
                            if token:
                                total_tokens += 1
                                yield f"event: token\ndata: {json.dumps({'text': token})}\n\n"
                                if total_tokens % 10 == 0:
                                    yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_tokens})}\n\n"
                        yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_tokens})}\n\n"
                        streamed = True
                        break
                    except Exception as e:
                        last_err = e
                        continue

            if not streamed:
                yield f"event: token\ndata: {json.dumps({'text': f'Groq error (all keys exhausted): {last_err}'})}\n\n"
        else:
            # Call Cloudflare stream with automatic Groq fallback
            url = f"https://api.cloudflare.com/client/v4/accounts/{cf_acc_id}/ai/run/{model_id}"
            headers = {
                "Authorization": f"Bearer {cf_token}",
                "Content-Type": "application/json"
            }
            payload = {
                "messages": messages,
                "max_tokens": 2048,
                "temperature": 0.2,
                "stream": True
            }

            try:
                resp = requests.post(url, headers=headers, json=payload, stream=True, timeout=60)
                if resp.status_code != 200:
                    raise RuntimeError(f"Cloudflare returned status {resp.status_code}: {resp.text}")

                in_thinking = False
                total_completion_tokens = 0

                for line in resp.iter_lines():
                    if not line:
                        continue
                    line_str = line.decode("utf-8")
                    if line_str.startswith("data: "):
                        raw_json = line_str[6:].strip()
                        if raw_json == "[DONE]":
                            break
                        try:
                            chunk_obj = json.loads(raw_json)
                            token = chunk_obj.get("response", "")
                            usage_obj = chunk_obj.get("usage")

                            if token:
                                total_completion_tokens += 1
                                if total_completion_tokens % 10 == 0:
                                    yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_completion_tokens})}\n\n"

                            if "<think>" in token:
                                in_thinking = True
                                token = token.replace("<think>", "")
                            if "</think>" in token:
                                parts = token.split("</think>", 1)
                                if parts[0]:
                                    yield f"event: thinking\ndata: {json.dumps({'text': parts[0]})}\n\n"
                                in_thinking = False
                                token = parts[1] if len(parts) > 1 else ""

                            if token:
                                if in_thinking:
                                    yield f"event: thinking\ndata: {json.dumps({'text': token})}\n\n"
                                else:
                                    yield f"event: token\ndata: {json.dumps({'text': token})}\n\n"

                            if usage_obj and isinstance(usage_obj, dict):
                                yield f"event: usage\ndata: {json.dumps(usage_obj)}\n\n"

                        except Exception:
                            pass

                yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_completion_tokens})}\n\n"

            except Exception as cf_err:
                # Automatic fallback to Groq Qwen 3.8-27b / LLaMA
                groq_clients = self.get_groq_clients_in_rotation()
                if groq_clients:
                    yield f"event: thinking\ndata: {json.dumps({'text': 'Cloudflare rate limited. Switching smoothly to Groq (with multi-key & model rotation)...'})}\n\n"
                    fallback_success = False
                    last_fallback_err = None
                    fallback_models = ["qwen/qwen3.8-27b", "qwen/qwen3.6-27b"]

                    for g_model in fallback_models:
                        if fallback_success:
                            break
                        max_tokens = 2000
                        for client in groq_clients:
                            try:
                                completion = client.chat.completions.create(
                                    model=g_model,
                                    messages=messages,
                                    temperature=0.6,
                                    max_completion_tokens=max_tokens,
                                    top_p=0.95,
                                    stream=True
                                )
                                total_tokens = 0
                                for chunk in completion:
                                    token = chunk.choices[0].delta.content or ""
                                    if token:
                                        total_tokens += 1
                                        yield f"event: token\ndata: {json.dumps({'text': token})}\n\n"
                                        if total_tokens % 10 == 0:
                                            yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_tokens})}\n\n"
                                yield f"event: usage\ndata: {json.dumps({'completion_tokens': total_tokens})}\n\n"
                                fallback_success = True
                                break
                            except Exception as groq_err:
                                last_fallback_err = groq_err
                                continue
                    if not fallback_success:
                        yield f"event: token\ndata: {json.dumps({'text': f'Error streaming from Groq fallback (all keys/models failed): {last_fallback_err}'})}\n\n"
                else:
                    yield f"event: token\ndata: {json.dumps({'text': f'Error streaming from Cloudflare: {cf_err}'})}\n\n"

        # Yield Stage 3: Citations
        if retrieved_chunks:
            yield f"event: citations\ndata: {json.dumps(retrieved_chunks)}\n\n"

        yield "event: done\ndata: {}\n\n"