File size: 59,119 Bytes
b9756ef
 
bfee845
b9756ef
bfee845
 
ea0c3e1
0634f1a
 
 
 
 
 
 
 
 
 
 
 
 
b9756ef
 
ea0c3e1
0634f1a
 
 
 
 
 
 
7c7cb71
 
 
 
ea0c3e1
408ac65
b9756ef
 
 
 
 
 
bfee845
b9756ef
0634f1a
 
 
 
 
 
 
 
b9756ef
 
7c7cb71
b9756ef
 
bfee845
b9756ef
bfee845
b9756ef
bfee845
 
 
b9756ef
bfee845
ea0c3e1
7c7cb71
0634f1a
bfee845
7c7cb71
 
0634f1a
 
bfee845
0634f1a
 
bfee845
7c7cb71
 
0634f1a
bfee845
0634f1a
ea0c3e1
bfee845
 
 
0634f1a
 
 
 
 
 
 
 
bfee845
0634f1a
 
 
 
 
b9756ef
0634f1a
 
 
 
 
 
 
b9756ef
0634f1a
 
 
 
 
 
 
 
bfee845
0634f1a
bfee845
0634f1a
bfee845
 
 
0634f1a
 
bfee845
0634f1a
bfee845
 
 
 
0634f1a
bfee845
 
 
 
 
0634f1a
 
bfee845
0634f1a
 
bfee845
 
 
0634f1a
 
 
 
 
 
bfee845
0634f1a
 
 
bfee845
 
0634f1a
 
 
bfee845
b9756ef
0634f1a
 
 
bfee845
 
 
0634f1a
 
 
 
bfee845
0634f1a
bfee845
b9756ef
bfee845
0634f1a
 
bfee845
0634f1a
 
bfee845
0634f1a
 
 
 
 
 
 
 
 
 
 
 
 
 
bfee845
0634f1a
 
7c7cb71
b9756ef
 
 
bfee845
0634f1a
 
 
 
 
b9756ef
0634f1a
 
ea0c3e1
b9756ef
bfee845
0634f1a
 
b9756ef
0634f1a
 
 
 
 
 
 
 
 
 
bfee845
0634f1a
 
 
b9756ef
bfee845
0634f1a
bfee845
408ac65
7c7cb71
0634f1a
408ac65
0634f1a
d55a911
0634f1a
d55a911
0634f1a
d55a911
56f099b
408ac65
bfee845
d55a911
408ac65
 
 
 
0634f1a
408ac65
 
 
bfee845
0634f1a
 
d55a911
 
56f099b
0634f1a
 
 
408ac65
0634f1a
 
 
 
b9756ef
0634f1a
56f099b
0634f1a
 
408ac65
 
 
 
d55a911
0634f1a
d55a911
408ac65
4c5479b
408ac65
 
d55a911
 
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55a911
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55a911
408ac65
 
 
 
 
d55a911
 
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55a911
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d55a911
408ac65
d55a911
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0634f1a
 
d55a911
408ac65
 
 
 
 
d55a911
408ac65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c5479b
 
d55a911
408ac65
56f099b
 
 
 
 
 
 
 
 
 
7c7cb71
408ac65
d55a911
 
0634f1a
 
d55a911
 
408ac65
0634f1a
7c7cb71
 
408ac65
d55a911
 
0634f1a
d55a911
 
 
 
0634f1a
408ac65
d55a911
 
56f099b
d55a911
408ac65
0634f1a
 
d55a911
 
0634f1a
d55a911
 
0634f1a
408ac65
56f099b
d55a911
 
408ac65
d55a911
0634f1a
408ac65
0634f1a
d55a911
 
 
 
0634f1a
d55a911
 
 
 
408ac65
56f099b
 
 
 
 
 
 
 
 
 
 
229d1b2
408ac65
7c7cb71
d55a911
7c7cb71
 
408ac65
 
 
 
 
 
d55a911
7c7cb71
408ac65
0634f1a
bfee845
408ac65
ea0c3e1
0634f1a
b9756ef
0634f1a
9e81792
 
bfee845
408ac65
0634f1a
 
bfee845
408ac65
0634f1a
408ac65
 
 
 
bfee845
408ac65
0634f1a
 
d55a911
0634f1a
 
408ac65
0634f1a
bfee845
408ac65
bfee845
408ac65
bfee845
cac7e1a
0634f1a
408ac65
d55a911
bfee845
b9756ef
d55a911
408ac65
0634f1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
import os
import logging
from typing import Dict, List, Optional
from functools import lru_cache
import re

import gradio as gr
try:
    from vector_db import VectorDatabase
except ImportError:
    print("Error: Could not import VectorDatabase from vector_db.py.")
    print("Please ensure vector_db.py exists in the same directory and is correctly defined.")
    exit(1)

try:
    from langchain_openai import ChatOpenAI
except ImportError:
    print("Error: langchain-openai not found. Please install it: pip install langchain-openai")
    exit(1)

from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain

# Suppress warnings
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)
warnings.filterwarnings("ignore", category=UserWarning, message=".*You are using gradio version.*")
warnings.filterwarnings("ignore", category=DeprecationWarning)

# Enhanced logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
)

# --- RAGSystem Class (Processing Logic - kept intact as requested) ---
class RAGSystem:
    def __init__(self, vector_db: Optional[VectorDatabase] = None):
        logging.info("Initializing RAGSystem")
        self.vector_db = vector_db if vector_db else VectorDatabase()
        self.llm = None
        self.chain = None
        self.prompt_template_str = """You are a legal assistant specializing in tenant rights and landlord-tenant laws. Your goal is to provide accurate, detailed, and helpful answers grounded in legal authority. Use the provided statutes as the primary source when available. If no relevant statutes are found in the context, rely on your general knowledge to provide a pertinent and practical response, clearly indicating when you are doing so and prioritizing state-specific information over federal laws for state-specific queries.
Instructions:
* Use the context and statutes as the primary basis for your answer when available.
* For state-specific queries, prioritize statutes or legal principles from the specified state over federal laws.
* Cite relevant statutes (e.g., (AS § 34.03.220(a)(2))) explicitly in your answer when applicable.
* If multiple statutes apply, list all relevant ones.
* If no specific statute is found in the context, state this clearly (e.g., 'No specific statute was found in the provided context'), then provide a general answer based on common legal principles or practices, marked as such.
* Include practical examples or scenarios to enhance clarity and usefulness.
* Use bullet points or numbered lists for readability when appropriate.
* Maintain a professional and neutral tone.
Question: {query}
State: {state}
Statutes from context:
{statutes}
Context information:
--- START CONTEXT ---
{context}
--- END CONTEXT ---
Answer:"""
        self.prompt_template = PromptTemplate(
            input_variables=["query", "context", "state", "statutes"],
            template=self.prompt_template_str
        )
        logging.info("RAGSystem initialized.")

    def extract_statutes(self, text: str) -> str:
        statute_pattern = r'\b(?:[A-Z]{2,}\.?\s+(?:Rev\.\s+)?Stat\.?|Code(?:\s+Ann\.?)?|Ann\.?\s+Laws|Statutes|CCP|USC|ILCS|Civ\.\s+Code|Penal\s+Code|Gen\.\s+Oblig\.\s+Law|R\.?S\.?|P\.?L\.?)\s+§\s*[\d\-]+(?:\.\d+)?(?:[\(\w\.\)]+)?|Title\s+\d+\s+USC\s+§\s*\d+(?:-\d+)?\b'
        statutes = re.findall(statute_pattern, text, re.IGNORECASE)
        valid_statutes = []
        for statute in statutes:
            statute = statute.strip()
            if '§' in statute and any(char.isdigit() for char in statute):
                 if not re.match(r'^\([\w\.]+\)$', statute) and 'http' not in statute:
                    if len(statute) > 5:
                        valid_statutes.append(statute)

        if valid_statutes:
            seen = set()
            unique_statutes = [s for s in valid_statutes if not (s.rstrip('.,;') in seen or seen.add(s.rstrip('.,;')))]
            logging.info(f"Extracted {len(unique_statutes)} unique statutes.")
            return "\n".join(f"- {s}" for s in unique_statutes)

        logging.info("No statutes found matching the pattern in the context.")
        return "No specific statutes found in the provided context."

    @lru_cache(maxsize=50)
    def process_query_cached(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
        logging.info(f"Processing query (cache key: '{query}'|'{state}'|key_hidden) with n_results={n_results}")

        if not state or state == "Select a state..." or "Error" in state:
            logging.warning("No valid state provided for query.")
            return {"answer": "<div class='error-message'>Error: Please select a valid state.</div>", "context_used": "N/A - Invalid Input"}
        if not query or not query.strip():
            logging.warning("No query provided.")
            return {"answer": "<div class='error-message'>Error: Please enter your question.</div>", "context_used": "N/A - Invalid Input"}
        if not openai_api_key or not openai_api_key.strip() or not openai_api_key.startswith("sk-"):
            logging.warning("No valid OpenAI API key provided.")
            return {"answer": "<div class='error-message'>Error: Please provide a valid OpenAI API key (starting with 'sk-'). Get one from <a href='https://platform.openai.com/api-keys' target='_blank'>OpenAI</a>.</div>", "context_used": "N/A - Invalid Input"}

        try:
            logging.info("Initializing temporary LLM and Chain for this query...")
            temp_llm = ChatOpenAI(
                temperature=0.2, openai_api_key=openai_api_key, model_name="gpt-3.5-turbo",
                max_tokens=1500, request_timeout=45
            )
            temp_chain = LLMChain(llm=temp_llm, prompt=self.prompt_template)
            logging.info("Temporary LLM and Chain initialized successfully.")
        except Exception as e:
            logging.error(f"LLM Initialization failed: {str(e)}", exc_info=True)
            error_msg = "Error: Failed to initialize AI model. Please check your network connection and API key validity."
            if "authentication" in str(e).lower():
                error_msg = "Error: OpenAI API Key is invalid or expired. Please check your key."
            return {"answer": f"<div class='error-message'>{error_msg}</div><div class='error-details'>Details: {str(e)}</div>", "context_used": "N/A - LLM Init Failed"}

        context = "No relevant context found."
        statutes_from_context = "Statute retrieval skipped due to context issues."
        try:
            logging.info(f"Querying Vector DB for query: '{query[:50]}...' in state '{state}'...")
            results = self.vector_db.query(query, state=state, n_results=n_results)
            logging.info(f"Vector DB query successful for state '{state}'. Processing results...")

            context_parts = []
            doc_results = results.get("document_results", {})
            docs = doc_results.get("documents", [[]])[0]
            metadatas = doc_results.get("metadatas", [[]])[0]
            if docs and metadatas and len(docs) == len(metadatas):
                logging.info(f"Found {len(docs)} document chunks.")
                for i, doc_content in enumerate(docs):
                    metadata = metadatas[i]
                    state_label = metadata.get('state', 'Unknown State')
                    chunk_id = metadata.get('chunk_id', 'N/A')
                    context_parts.append(f"**Source: Document Chunk {chunk_id} (State: {state_label})**\n{doc_content}")

            state_results_data = results.get("state_results", {})
            state_docs = state_results_data.get("documents", [[]])[0]
            state_metadatas = state_results_data.get("metadatas", [[]])[0]
            if state_docs and state_metadatas and len(state_docs) == len(state_metadatas):
                logging.info(f"Found {len(state_docs)} state summary documents.")
                for i, state_doc_content in enumerate(state_docs):
                    metadata = state_metadatas[i]
                    state_label = metadata.get('state', state)
                    context_parts.append(f"**Source: State Summary (State: {state_label})**\n{state_doc_content}")

            if context_parts:
                context = "\n\n---\n\n".join(context_parts)
                logging.info(f"Constructed context with {len(context_parts)} parts. Length: {len(context)} chars.")
                try:
                    statutes_from_context = self.extract_statutes(context)
                except Exception as e:
                    logging.error(f"Error extracting statutes: {e}", exc_info=True)
                    statutes_from_context = "Error extracting statutes from context."
            else:
                logging.warning("No relevant context parts found from vector DB query.")
                context = "No relevant context could be retrieved from the knowledge base for this query and state. The AI will answer from its general knowledge."
                statutes_from_context = "No specific statutes found as no context was retrieved."

        except Exception as e:
            logging.error(f"Vector DB query/context processing failed: {str(e)}", exc_info=True)
            context = f"Warning: Error retrieving documents from the knowledge base ({str(e)}). The AI will attempt to answer from its general knowledge, which may be less specific or accurate."
            statutes_from_context = "Statute retrieval skipped due to error retrieving context."

        try:
            logging.info("Invoking LLMChain with constructed input...")
            llm_input = {"query": query, "context": context, "state": state, "statutes": statutes_from_context}
            answer_dict = temp_chain.invoke(llm_input)
            answer_text = answer_dict.get('text', '').strip()

            if not answer_text:
                logging.warning("LLM returned an empty answer.")
                answer_text = "<div class='error-message'>The AI model returned an empty response. This might be due to the query, context limitations, or temporary issues. Please try rephrasing your question or try again later.</div>"
            else:
                logging.info("LLM generated answer successfully.")

            return {"answer": answer_text, "context_used": context}

        except Exception as e:
            logging.error(f"LLM processing failed: {str(e)}", exc_info=True)
            error_message = "Error: AI answer generation failed."
            details = f"Details: {str(e)}"
            if "authentication" in str(e).lower():
                error_message = "Error: Authentication failed. Please double-check your OpenAI API key."
                details = ""
            elif "rate limit" in str(e).lower():
                error_message = "Error: You've exceeded your OpenAI API rate limit or quota. Please check your usage and plan limits, or wait and try again."
                details = ""
            elif "context length" in str(e).lower():
                error_message = "Error: The request was too long for the AI model. This can happen with very complex questions or extensive retrieved context."
                details = "Try simplifying your question or asking about a more specific aspect."
            elif "timeout" in str(e).lower():
                 error_message = "Error: The request to the AI model timed out. The service might be busy."
                 details = "Please try again in a few moments."

            formatted_error = f"<div class='error-message'>{error_message}</div>"
            if details:
                formatted_error += f"<div class='error-details'>{details}</div>"

            return {"answer": formatted_error, "context_used": context}

    def process_query(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
        return self.process_query_cached(query.strip(), state, openai_api_key.strip(), n_results)

    def get_states(self) -> List[str]:
        try:
            states = self.vector_db.get_states()
            if not states:
                logging.warning("No states retrieved from vector_db. Returning empty list.")
                return []
            valid_states = sorted(list(set(s for s in states if s and isinstance(s, str) and s != "Select a state...")))
            logging.info(f"Retrieved {len(valid_states)} unique, valid states from VectorDatabase.")
            return valid_states
        except Exception as e:
            logging.error(f"Failed to get states from VectorDatabase: {str(e)}", exc_info=True)
            return ["Error: Could not load states"]

    def load_pdf(self, pdf_path: str) -> int:
        if not os.path.exists(pdf_path):
            logging.error(f"PDF file not found at path: {pdf_path}")
            raise FileNotFoundError(f"PDF file not found: {pdf_path}")
        try:
            logging.info(f"Attempting to load/verify data from PDF: {pdf_path}")
            num_states_processed = self.vector_db.process_and_load_pdf(pdf_path)
            doc_count = self.vector_db.document_collection.count()
            state_count = self.vector_db.state_collection.count()
            total_items = doc_count + state_count

            if total_items > 0:
                logging.info(f"Vector DB contains {total_items} items ({doc_count} docs, {state_count} states). PDF processed or data already existed.")
                current_states = self.get_states()
                return len(current_states) if current_states and "Error" not in current_states[0] else 0
            else:
                logging.warning(f"PDF processing completed, but the vector database appears empty. Check PDF content and processing logs.")
                return 0

        except Exception as e:
            logging.error(f"Failed to load or process PDF '{pdf_path}': {str(e)}", exc_info=True)
            raise RuntimeError(f"Failed to process PDF '{pdf_path}': {e}") from e

    # --- GRADIO INTERFACE (Completely Redesigned UI) ---
    def gradio_interface(self):
        def query_interface_wrapper(api_key: str, query: str, state: str) -> str:
            # Basic client-side validation for immediate feedback
            if not api_key or not api_key.strip() or not api_key.startswith("sk-"):
                 return "<div class='error-message'><span class='error-icon'>⚠️</span>Please provide a valid OpenAI API key (starting with 'sk-'). <a href='https://platform.openai.com/api-keys' target='_blank'>Get one here</a>.</div>"
            if not state or state == "Select a state..." or "Error" in state:
                return "<div class='error-message'><span class='error-icon'>⚠️</span>Please select a valid state from the dropdown.</div>"
            if not query or not query.strip():
                return "<div class='error-message'><span class='error-icon'>⚠️</span>Please enter your question in the text box.</div>"

            # Call the core processing logic
            result = self.process_query(query=query, state=state, openai_api_key=api_key)
            answer = result.get("answer", "<div class='error-message'><span class='error-icon'>⚠️</span>An unexpected error occurred.</div>")

            # Check if the answer already contains an error message (from deeper within process_query)
            if "<div class='error-message'>" in answer:
                 return answer # Return the pre-formatted error message directly
            else:
                 # Format the successful response with the new UI structure
                 formatted_response = f"<div class='response-header'><span class='response-icon'>📜</span>Response for {state}</div><hr class='divider'>{answer}"
                 return formatted_response

        try:
            available_states_list = self.get_states()
            dropdown_choices = ["Select a state..."] + (available_states_list if available_states_list and "Error" not in available_states_list[0] else ["Error: States unavailable"])
            initial_value = dropdown_choices[0]
        except Exception: # Catch-all for safety
            dropdown_choices = ["Error: Critical failure loading states"]
            initial_value = dropdown_choices[0]

        # Define example queries, filtering based on available states
        example_queries_base = [
            ["What are the rules for security deposit returns?", "California"],
            ["Can a landlord enter my apartment without notice?", "New York"],
            ["My landlord hasn't made necessary repairs. What can I do?", "Texas"],
        ]
        example_queries = []
        if available_states_list and "Error" not in available_states_list[0] and len(available_states_list) > 0:
            loaded_states_set = set(available_states_list)
            example_queries = [ex for ex in example_queries_base if ex[1] in loaded_states_set]
            # Add a generic example if no specific state examples match or if list is empty
            if not example_queries:
                 example_queries.append(["What basic rights do tenants have?", available_states_list[0] if available_states_list else "California"])
        else: # Fallback if states list is problematic
            example_queries.append(["What basic rights do tenants have?", "California"])


        # --- Custom CSS for "Legal Lumen" Theme ---
        custom_css = """
        /* New Theme: Legal Lumen */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Montserrat:wght@600;700;800&display=swap');

        :root {
            /* Light Theme Colors */
            --app-bg-light: #F8F9FA; /* Very light gray */
            --surface-bg-light: #FFFFFF; /* Pure white for cards */
            --text-primary-light: #212529; /* Dark charcoal */
            --text-secondary-light: #6C757D; /* Muted gray */
            --accent-main-light: #007bff; /* Vibrant professional blue */
            --accent-hover-light: #0056b3; /* Darker blue on hover */
            --accent-secondary-light: #6C757D; /* For secondary buttons, similar to text secondary */
            --accent-secondary-hover-light: #5A6268; /* Darker secondary hover */
            --border-light: #DEE2E6; /* Light border */
            --shadow-light: 0 0.5rem 1rem rgba(0,0,0,0.08); /* Subtle shadow */
            --focus-ring-light: rgba(0, 123, 255, 0.25); /* Blue focus ring */
            --error-bg-light: #F8D7DA; /* Light red for error backgrounds */
            --error-text-light: #721C24; /* Dark red for error text */
            --error-border-light: #F5C6CB; /* Red border for errors */

            /* Dark Theme Colors */
            --app-bg-dark: #212529; /* Deep dark gray */
            --surface-bg-dark: #343A40; /* Slightly lighter dark gray for cards */
            --text-primary-dark: #F8F9FA; /* Off-white */
            --text-secondary-dark: #ADB5BD; /* Muted light gray */
            --accent-main-dark: #8AB4F8; /* Lighter blue for dark mode */
            --accent-hover-dark: #669DF6; /* Darker blue on hover for dark mode */
            --accent-secondary-dark: #ADB5BD; /* For secondary buttons in dark mode */
            --accent-secondary-hover-dark: #97A0A8; /* Darker secondary hover in dark mode */
            --border-dark: #495057; /* Dark border */
            --shadow-dark: 0 0.5rem 1rem rgba(0,0,0,0.3); /* Darker shadow */
            --focus-ring-dark: rgba(138, 180, 248, 0.35); /* Muted blue focus ring for dark mode */
            --error-bg-dark: #721C24; /* Dark red for error backgrounds */
            --error-text-dark: #F8D7DA; /* Light red for error text */
            --error-border-dark: #F5C6CB; /* Red border for errors */

            /* General Styling Variables */
            --font-family-main: 'Inter', sans-serif;
            --font-family-header: 'Montserrat', sans-serif;
            --radius-sm: 4px; /* Small border radius */
            --radius-md: 8px; /* Medium border radius */
            --radius-lg: 12px; /* Large border radius */
            --transition-speed: 0.25s; /* Standard transition duration */
        }

        /* Base styles for the entire app */
        body, .gradio-container {
            font-family: var(--font-family-main) !important;
            background: var(--app-bg-light) !important;
            color: var(--text-primary-light) !important;
            margin: 0;
            padding: 0;
            min-height: 100vh;
            font-size: 16px;
            line-height: 1.6; /* Improved readability */
            -webkit-font-smoothing: antialiased; /* Smoother fonts */
            -moz-osx-font-smoothing: grayscale;
        }
        * { box-sizing: border-box; } /* Ensure consistent box model */

        /* Dark mode preference (applies styles when user's system is in dark mode) */
        @media (prefers-color-scheme: dark) {
            body, .gradio-container {
                background: var(--app-bg-dark) !important;
                color: var(--text-primary-dark) !important;
            }
        }

        /* Global container styling: max-width for content, centering, and padding */
        .gradio-container > .flex.flex-col {
            max-width: 900px; /* Slightly wider for better content flow */
            margin: 0 auto !important; /* Center the container */
            padding: 2rem 1.5rem 4rem 1.5rem !important; /* Generous top, side, and bottom padding */
            gap: 0 !important; /* Remove Gradio's default gap, manage spacing with element margins */
        }

        /* Header section styling: prominent, rounded banner */
        .app-header-wrapper {
            background: linear-gradient(135deg, var(--accent-main-light) 0%, var(--accent-hover-light) 100%); /* Gradient background for depth */
            color: #FFFFFF !important; /* White text for light theme header */
            padding: 3rem 2rem 4rem 2rem !important; /* More vertical padding for impact */
            text-align: center !important;
            border-radius: var(--radius-lg); /* Rounded corners for the header card */
            box-shadow: var(--shadow-light);
            margin-bottom: 3.5rem; /* Spacing between header and first content card */
            position: relative; /* For animation context */
            overflow: hidden; /* Ensure content stays within rounded corners */
        }
        .app-header {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 1; /* Keep content above any potential background effects */
        }
        .app-header-logo {
            font-size: 4rem; /* Larger icon */
            margin-bottom: 1rem;
            display: block;
            line-height: 1; /* Prevent extra space below emoji */
            animation: bounceIn 0.8s ease-out; /* Simple entry animation for logo */
        }
        .app-header-title {
            font-family: var(--font-family-header) !important;
            font-size: 2.8rem; /* Much larger and bolder */
            font-weight: 800; /* Extra bold */
            margin: 0 0 0.75rem 0;
            letter-spacing: -0.04em; /* Tighter letter spacing for a modern look */
            text-shadow: 0 2px 4px rgba(0,0,0,0.2); /* Subtle text shadow for depth */
            animation: fadeInDown 1s ease-out; /* Entry animation for title */
        }
        .app-header-tagline {
            font-family: var(--font-family-main) !important;
            font-size: 1.25rem; /* Slightly larger tagline */
            font-weight: 300;
            opacity: 0.9;
            max-width: 600px;
            animation: fadeInUp 1s ease-out; /* Entry animation for tagline */
        }

        /* Dark mode header adjustments */
        @media (prefers-color-scheme: dark) {
            .app-header-wrapper {
                background: linear-gradient(135deg, var(--accent-main-dark) 0%, var(--accent-hover-dark) 100%);
                box-shadow: var(--shadow-dark);
            }
            .app-header-title { color: var(--text-primary-dark) !important; } /* Ensure title color adjusts for dark theme */
        }

        /* Keyframe animations for header elements */
        @keyframes bounceIn {
            0%, 20%, 40%, 60%, 80%, 100% {
                -webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
                transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
            }
            0% { opacity: 0; -webkit-transform: scale3d(0.3, 0.3, 0.3); transform: scale3d(0.3, 0.3, 0.3); }
            20% { -webkit-transform: scale3d(1.1, 1.1, 1.1); transform: scale3d(1.1, 1.1, 1.1); }
            40% { -webkit-transform: scale3d(0.9, 0.9, 0.9); transform: scale3d(0.9, 0.9, 0.9); }
            60% { opacity: 1; -webkit-transform: scale3d(1.03, 1.03, 1.03); transform: scale3d(1.03, 1.03, 1.03); }
            80% { -webkit-transform: scale3d(0.97, 0.97, 0.97); transform: scale3d(0.97, 0.97, 0.97); }
            100% { opacity: 1; -webkit-transform: scale3d(1, 1, 1); transform: scale3d(1, 1, 1); }
        }

        @keyframes fadeInDown {
            from { opacity: 0; transform: translate3d(0, -20px, 0); }
            to { opacity: 1; transform: translate3d(0, 0, 0); }
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translate3d(0, 20px, 0); }
            to { opacity: 1; transform: translate3d(0, 0, 0); }
        }


        /* Styling for general content cards (surface elements) */
        .content-surface {
            background: var(--surface-bg-light) !important;
            border-radius: var(--radius-lg) !important;
            padding: 3rem !important; /* Consistent padding */
            box-shadow: var(--shadow-light) !important;
            border: 1px solid var(--border-light) !important;
            margin-bottom: 3rem; /* Spacing between cards */
            transition: background var(--transition-speed), border-color var(--transition-speed), box-shadow var(--transition-speed);
        }
        .content-surface:last-child { margin-bottom: 0; } /* No bottom margin for the last surface */
        @media (prefers-color-scheme: dark) {
            .content-surface {
                background: var(--surface-bg-dark) !important;
                box-shadow: var(--shadow-dark) !important;
                border: 1px solid var(--border-dark) !important;
            }
        }

        /* Section titles within content cards: centered, bold, with a clear separator */
        .section-title, .input-form-card h3, .examples-card .gr-examples-header {
            font-family: var(--font-family-header) !important;
            font-size: 1.65rem !important; /* Slightly larger than before */
            font-weight: 600 !important;
            color: var(--text-primary-light) !important;
            margin: 0 auto 2.2rem auto !important; /* Centered, with more space below title */
            padding-bottom: 1rem !important;
            border-bottom: 2px solid var(--border-light) !important; /* Thicker separator for emphasis */
            text-align: center !important;
            width: 100%;
        }
        @media (prefers-color-scheme: dark) {
            .section-title, .input-form-card h3, .examples-card .gr-examples-header {
                color: var(--text-primary-dark) !important;
                border-bottom-color: var(--border-dark) !important;
            }
        }

        /* General text styling within content surfaces */
        .content-surface p {
            font-size: 1.05rem; /* Slightly larger body text for readability */
            line-height: 1.7; /* Generous line height */
            color: var(--text-secondary-light);
            margin-bottom: 1rem;
        }
        .content-surface a {
            color: var(--accent-main-light);
            text-decoration: none;
            font-weight: 500;
            transition: color var(--transition-speed), text-decoration var(--transition-speed);
        }
        .content-surface a:hover {
            color: var(--accent-hover-light);
            text-decoration: underline;
        }
        .content-surface strong {
            font-weight: 600;
            color: var(--text-primary-light);
        }
        @media (prefers-color-scheme: dark) {
            .content-surface p { color: var(--text-secondary-dark); }
            .content-surface a { color: var(--accent-main-dark); }
            .content-surface a:hover { color: var(--accent-hover-dark); }
            .content-surface strong { color: var(--text-primary-dark); }
        }

        /* Input field group and layout: organized and symmetric */
        .input-field-group { margin-bottom: 2rem; }
        .input-row {
            display: flex;
            gap: 2rem; /* Increased gap for better spacing */
            flex-wrap: wrap; /* Allow wrapping on smaller screens */
            margin-bottom: 2.5rem; /* More space before buttons */
        }
        .input-field {
            flex: 1; /* Distribute space evenly */
            min-width: 280px; /* Adjusted minimum width before wrapping */
        }

        /* Input labels and info text */
        .gradio-input-label {
            font-size: 1rem !important; /* Slightly larger label */
            font-weight: 500 !important;
            color: var(--text-primary-light) !important;
            margin-bottom: 0.6rem !important;
            display: block !important;
        }
        .gradio-input-info {
            font-size: 0.85rem !important;
            color: var(--text-secondary-light) !important;
            margin-top: 0.4rem;
        }
        @media (prefers-color-scheme: dark) {
            .gradio-input-label { color: var(--text-primary-dark) !important; }
            .gradio-input-info { color: var(--text-secondary-dark) !important; }
        }

        /* Textbox, Dropdown, Password input styling: larger and more padded */
        .gradio-textbox textarea,
        .gradio-dropdown select,
        .gradio-textbox input[type=password] {
            border: 1px solid var(--border-light) !important;
            border-radius: var(--radius-md) !important;
            padding: 1rem 1.2rem !important; /* More padding */
            font-size: 1.05rem !important; /* Larger font size */
            background: var(--surface-bg-light) !important;
            color: var(--text-primary-light) !important;
            width: 100% !important;
            box-shadow: none !important;
            transition: border-color var(--transition-speed), box-shadow var(--transition-speed);
        }
        .gradio-textbox textarea { min-height: 140px; } /* Taller textarea for more input visibility */
        .gradio-textbox textarea::placeholder,
        .gradio-textbox input[type=password]::placeholder {
            color: #A0AEC0 !important; /* Consistent placeholder color */
        }
        .gradio-textbox textarea:focus,
        .gradio-dropdown select:focus,
        .gradio-textbox input[type=password]:focus {
            border-color: var(--accent-main-light) !important;
            box-shadow: 0 0 0 3px var(--focus-ring-light) !important; /* Accent color focus ring */
            outline: none !important;
        }
        @media (prefers-color-scheme: dark) {
            .gradio-textbox textarea,
            .gradio-dropdown select,
            .gradio-textbox input[type=password] {
                border: 1px solid var(--border-dark) !important;
                background: var(--surface-bg-dark) !important;
                color: var(--text-primary-dark) !important;
            }
            .gradio-textbox textarea::placeholder,
            .gradio-textbox input[type=password]::placeholder {
                color: #718096 !important;
            }
            .gradio-textbox textarea:focus,
            .gradio-dropdown select:focus,
            .gradio-textbox input[type=password]:focus {
                border-color: var(--accent-main-dark) !important;
                box-shadow: 0 0 0 3px var(--focus-ring-dark) !important;
            }
        }

        /* Custom dropdown arrow for consistent look (re-applied for new colors) */
        .gradio-dropdown select {
            appearance: none; /* Remove native arrow */
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%236C757D%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.293%207.293a1%201%200%20011.414%200L10%2010.586l3.293-3.293a1%201%200%20111.414%201.414l-4%204a1%201%200%2001-1.414%200l-4-4a1%201%200%20010-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E');
            background-repeat: no-repeat;
            background-position: right 1.2rem center; /* Adjusted position */
            background-size: 1.1em; /* Slightly larger arrow */
            padding-right: 3.5rem !important; /* Make space for arrow */
        }
        @media (prefers-color-scheme: dark) {
            .gradio-dropdown select {
                background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%23ADB5BD%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.293%207.293a1%201%200%20011.414%200L10%2010.586l3.293-3.293a1%201%200%20111.414%201.414l-4%204a1%201%200%2001-1.414%200l-4-4a1%201%200%20010-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E');
            }
        }

        /* Button group and styling: dynamic and clear actions */
        .button-row {
            display: flex;
            gap: 1.5rem; /* More space between buttons */
            margin-top: 2rem;
            flex-wrap: wrap;
            justify-content: flex-end; /* Align buttons to the right */
        }
        .gradio-button {
            border-radius: var(--radius-md) !important;
            padding: 0.9rem 2rem !important; /* More padding */
            font-size: 1.05rem !important; /* Larger font */
            font-weight: 500 !important;
            border: 1px solid transparent !important;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1); /* Subtle shadow for primary */
            transition: all var(--transition-speed) ease; /* Smooth transition for hover/active states */
        }
        .gradio-button:hover:not(:disabled) {
            transform: translateY(-3px); /* More pronounced lift on hover */
            box-shadow: 0 6px 12px rgba(0,0,0,0.15) !important;
        }
        .gradio-button:active:not(:disabled) { transform: translateY(-1px); } /* Slight press effect */
        .gradio-button:disabled {
            background: #E9ECEF !important;
            color: #ADB5BD !important;
            box-shadow: none !important;
            border-color: #DEE2E6 !important;
            cursor: not-allowed;
        }

        /* Primary button (Submit Query) */
        .gr-button-primary {
            background: var(--accent-main-light) !important;
            color: #FFFFFF !important;
            border-color: var(--accent-main-light) !important;
        }
        .gr-button-primary:hover:not(:disabled) {
            background: var(--accent-hover-light) !important;
            border-color: var(--accent-hover-light) !important;
        }

        /* Secondary button (Clear) */
        .gr-button-secondary {
            background: transparent !important; /* Transparent background */
            color: var(--accent-secondary-light) !important;
            border-color: var(--accent-secondary-light) !important; /* Border in accent color */
            box-shadow: none !important; /* No shadow for secondary button */
        }
        .gr-button-secondary:hover:not(:disabled) {
            background: rgba(0, 123, 255, 0.05) !important; /* Very light hover background */
            color: var(--accent-hover-light) !important;
            border-color: var(--accent-hover-light) !important;
            box-shadow: none !important;
        }

        @media (prefers-color-scheme: dark) {
            .gradio-button { box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important; }
            .gradio-button:hover:not(:disabled) { box-shadow: 0 6px 12px rgba(0,0,0,0.3) !important; }
            .gradio-button:disabled {
                background: #495057 !important;
                color: #6C757D !important;
                border-color: #6C757D !important;
            }
            .gr-button-primary {
                background: var(--accent-main-dark) !important;
                color: var(--text-primary-dark) !important; /* Text color contrasts with dark accent */
                border-color: var(--accent-main-dark) !important;
            }
            .gr-button-primary:hover:not(:disabled) {
                background: var(--accent-hover-dark) !important;
                border-color: var(--accent-hover-dark) !important;
            }
            .gr-button-secondary {
                background: transparent !important;
                color: var(--accent-secondary-dark) !important;
                border-color: var(--accent-secondary-dark) !important;
            }
            .gr-button-secondary:hover:not(:disabled) {
                background: rgba(138, 180, 248, 0.1) !important; /* Light blue hover for dark secondary */
                color: var(--accent-hover-dark) !important;
                border-color: var(--accent-hover-dark) !important;
            }
        }

        /* Output Card Styling: clear structure for answers */
        .output-card .response-header {
            font-size: 1.4rem; /* Larger header */
            font-weight: 600;
            color: var(--text-primary-light);
            margin: 0 0 1.2rem 0;
            display: flex;
            align-items: center;
            gap: 0.8rem; /* Space between icon and text */
        }
        .output-card .response-icon {
            font-size: 1.6rem;
            color: var(--accent-main-light); /* Accent color for icon */
        }
        .output-card .divider {
            border: none;
            border-top: 1px solid var(--border-light);
            margin: 1.5rem 0 2rem 0; /* More spacing around divider */
        }
        .output-card .output-content-wrapper {
            font-size: 1.05rem;
            line-height: 1.7;
            color: var(--text-primary-light);
        }
        .output-card .output-content-wrapper p { margin-bottom: 1rem; }
        .output-card .output-content-wrapper ul,
        .output-card .output-content-wrapper ol {
            margin-left: 1.8rem; /* More indentation for lists */
            margin-bottom: 1rem;
            padding-left: 0;
            list-style-type: disc; /* Ensure consistent bullet style */
        }
        .output-card .output-content-wrapper ol { list-style-type: decimal; } /* Numbered lists */
        .output-card .output-content-wrapper li { margin-bottom: 0.6rem; }
        .output-card .output-content-wrapper strong { font-weight: 700; } /* Bolder strong text within output */
        .output-card .output-content-wrapper a {
            color: var(--accent-main-light);
            text-decoration: underline; /* Links in output should be underlined for clarity */
        }
        .output-card .output-content-wrapper a:hover {
            color: var(--accent-hover-light);
        }

        @media (prefers-color-scheme: dark) {
            .output-card .response-header { color: var(--text-primary-dark); }
            .output-card .response-icon { color: var(--accent-main-dark); }
            .output-card .divider { border-top: 1px solid var(--border-dark); }
            .output-card .output-content-wrapper { color: var(--text-primary-dark); }
            .output-card .output-content-wrapper a { color: var(--accent-main-dark); }
            .output-card .output-content-wrapper a:hover { color: var(--accent-hover-dark); }
        }

        /* Error and Success Messages: visually distinct and informative */
        .output-card .error-message {
            padding: 1rem 1.5rem;
            margin-top: 1.5rem;
            font-size: 1rem;
            border-radius: var(--radius-md);
            background: var(--error-bg-light);
            color: var(--error-text-light);
            border: 1px solid var(--error-border-light);
            display: flex; /* Use flexbox for icon and text alignment */
            align-items: flex-start; /* Align text to top if icon is taller */
            gap: 0.8em;
        }
        .output-card .error-message .error-icon {
            font-size: 1.4rem;
            line-height: 1; /* Ensure icon is vertically centered */
            padding-top: 0.1em; /* Fine tune vertical alignment */
        }
        .output-card .error-details {
            font-size: 0.9rem;
            margin-top: 0.6rem;
            opacity: 0.9;
            word-break: break-word; /* Prevent long URLs/messages from overflowing */
        }
        @media (prefers-color-scheme: dark) {
            .output-card .error-message {
                background: var(--error-bg-dark);
                color: var(--error-text-dark);
                border: 1px solid var(--error-border-dark);
            }
        }

        /* Placeholder styling for empty output area */
        .output-card .placeholder {
            padding: 3.5rem 1.5rem; /* More vertical padding */
            font-size: 1.15rem; /* Larger placeholder text */
            border-radius: var(--radius-lg);
            border: 2px dashed var(--border-light);
            color: var(--text-secondary-light);
            text-align: center;
            opacity: 0.8;
        }
        @media (prefers-color-scheme: dark) {
            .output-card .placeholder {
                border-color: var(--border-dark);
                color: var(--text-secondary-dark);
            }
        }

        /* Examples table styling: clean and interactive */
        .examples-card .gr-examples-table {
            border-radius: var(--radius-lg) !important;
            border: 1px solid var(--border-light) !important;
            overflow: hidden; /* Ensures border-radius is applied to table */
        }
        .examples-card .gr-examples-table th,
        .examples-card .gr-examples-table td {
            padding: 1rem 1.2rem !important; /* More padding */
            font-size: 0.98rem !important;
            border: none !important; /* Remove individual cell borders */
        }
        .examples-card .gr-examples-table th {
            background: var(--app-bg-light) !important; /* Match app background for table header for seamless look */
            color: var(--text-primary-light) !important;
            font-weight: 600 !important;
            text-align: left;
        }
        .examples-card .gr-examples-table td {
            background: var(--surface-bg-light) !important;
            color: var(--text-primary-light) !important;
            border-top: 1px solid var(--border-light) !important; /* Add horizontal rule between rows */
            cursor: pointer; /* Indicate clickable rows */
            transition: background var(--transition-speed);
        }
        .examples-card .gr-examples-table tr:hover td {
            background: rgba(0, 123, 255, 0.03) !important; /* Very light hover effect */
        }
        .examples-card .gr-examples-table tr:first-child td { border-top: none !important; } /* No top border for first row's cells */

        @media (prefers-color-scheme: dark) {
            .examples-card .gr-examples-table { border: 1px solid var(--border-dark) !important;}
            .examples-card .gr-examples-table th {
                background: var(--app-bg-dark) !important;
                color: var(--text-primary-dark) !important;
            }
            .examples-card .gr-examples-table td {
                background: var(--surface-bg-dark) !important;
                color: var(--text-primary-dark) !important;
                border-top: 1px solid var(--border-dark) !important;
            }
            .examples-card .gr-examples-table tr:hover td {
                background: rgba(138, 180, 248, 0.1) !important; /* Light blue hover for dark table */
            }
        }

        /* Footer styling: clean and informative */
        .app-footer-wrapper {
            border-top: 1px solid var(--border-light) !important;
            margin-top: 3.5rem; /* Spacing from last content card */
            padding-top: 3rem; /* Padding above footer content */
        }
        .app-footer {
            padding: 0 1.5rem !important;
            text-align: center !important;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .app-footer p {
            font-size: 0.95rem !important;
            color: var(--text-secondary-light) !important;
            margin-bottom: 0.8rem;
            max-width: 650px; /* Constrain text width for readability */
        }
        .app-footer a {
            color: var(--accent-main-light) !important;
            font-weight: 500;
            transition: color var(--transition-speed), text-decoration var(--transition-speed);
        }
        .app-footer a:hover {
            color: var(--accent-hover-light) !important;
            text-decoration: underline;
        }
        @media (prefers-color-scheme: dark) {
            .app-footer-wrapper { border-top-color: var(--border-dark) !important; }
            .app-footer p { color: var(--text-secondary-dark) !important; }
            .app-footer a { color: var(--accent-main-dark) !important; }
            .app-footer a:hover { color: var(--accent-hover-dark) !important; }
        }

        /* Accessibility: Focus styles for keyboard navigation */
        :focus-visible {
            outline: 2px solid var(--accent-main-light) !important;
            outline-offset: 2px;
            box-shadow: 0 0 0 4px var(--focus-ring-light) !important; /* Thicker, more visible focus ring */
        }
        @media (prefers-color-scheme: dark) {
            :focus-visible {
                outline-color: var(--accent-main-dark) !important;
                box-shadow: 0 0 0 4px var(--focus-ring-dark) !important;
            }
        }
        /* Prevent double focus outline on Gradio buttons' internal span */
        .gradio-button span:focus { outline: none !important; }


        /* Essential overrides to ensure custom styles take precedence over Gradio defaults */
        .gradio-container > .flex { gap: 0 !important; } /* Remove main container gap */
        .gradio-markdown > *:first-child { margin-top: 0; } /* Remove top margin from first element in Markdown */
        .gradio-markdown > *:last-child { margin-bottom: 0; } /* Remove bottom margin from last element in Markdown */
        /* Remove default Gradio component borders/padding that interfere with custom styling */
        .gradio-dropdown, .gradio-textbox { border: none !important; padding: 0 !important; background: transparent !important; }

        /* Responsive adjustments for various screen sizes */
        @media (max-width: 992px) {
            .gradio-container > .flex.flex-col { max-width: 760px; padding: 1.5rem 1.25rem 3.5rem 1.25rem !important; }
            .content-surface { padding: 2.5rem !important; margin-bottom: 2.5rem; }
            .app-header-wrapper { padding: 2.5rem 1.5rem 3.5rem 1.5rem !important; margin-bottom: 3rem; }
            .app-header-title { font-size: 2.5rem; }
            .app-header-tagline { font-size: 1.15rem; }
            .section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.5rem !important; margin-bottom: 2rem !important; }
            .input-row { gap: 1.5rem; }
            .gradio-textbox textarea { min-height: 120px; }
        }

        @media (max-width: 768px) {
            .gradio-container > .flex.flex-col { padding: 1rem 1rem 3rem 1rem !important; }
            .content-surface { padding: 2rem !important; margin-bottom: 2rem; }
            .app-header-wrapper { padding: 2rem 1.25rem 3rem 1.25rem !important; margin-bottom: 2.5rem; }
            .app-header-logo { font-size: 3.5rem; }
            .app-header-title { font-size: 2.2rem; letter-spacing: -0.03em; }
            .app-header-tagline { font-size: 1.05rem; }
            .section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.4rem !important; margin-bottom: 1.8rem !important; }
            .input-row { flex-direction: column; gap: 1.25rem; } /* Stack inputs vertically */
            .input-field { min-width: 100%; }
            .button-row { justify-content: stretch; } /* Stretch buttons to full width */
            .gradio-button { width: 100%; }
            .output-card .response-header { font-size: 1.25rem; }
            .output-card .response-icon { font-size: 1.4rem; }
            .output-card .placeholder { padding: 3rem 1rem; font-size: 1.1rem; }
            .examples-card .gr-examples-table th, .examples-card .gr-examples-table td { padding: 0.8rem 1rem !important; font-size: 0.95rem !important; }
            .app-footer-wrapper { margin-top: 3rem; padding-top: 2.5rem; }
            .app-footer p { font-size: 0.9rem !important; }
        }

        @media (max-width: 480px) {
            .gradio-container > .flex.flex-col { padding: 0.75rem 0.75rem 2.5rem 0.75rem !important; }
            .content-surface { padding: 1.5rem !important; margin-bottom: 1.5rem; border-radius: var(--radius-md) !important; }
            .app-header-wrapper { padding: 1.5rem 1rem 2rem 1rem !important; margin-bottom: 2rem; border-radius: var(--radius-md); }
            .app-header-logo { font-size: 3rem; margin-bottom: 0.75rem; }
            .app-header-title { font-size: 2rem; letter-spacing: -0.02em; }
            .app-header-tagline { font-size: 0.95rem; }
            .section-title, .input-form-card h3, .examples-card .gr-examples-header { font-size: 1.25rem !important; margin-bottom: 1.5rem !important; padding-bottom: 0.75rem !important; }
            .gradio-textbox textarea, .gradio-dropdown select, .gradio-textbox input[type=password] { font-size: 0.95rem !important; padding: 0.8rem 1rem !important; }
            .gradio-textbox textarea { min-height: 100px; }
            .gradio-button { padding: 0.8rem 1.2rem !important; font-size: 0.95rem !important; }
            .output-card .response-header { font-size: 1.15rem; }
            .output-card .response-icon { font-size: 1.3rem; }
            .output-card .placeholder { padding: 2.5rem 0.8rem; font-size: 1rem; }
            .examples-card .gr-examples-table th, .examples-card .gr-examples-table td { padding: 0.6rem 0.8rem !important; font-size: 0.85rem !important; }
            .app-footer-wrapper { margin-top: 2.5rem; padding-top: 2rem; }
            .app-footer p { font-size: 0.85rem !important; }
        }
        """

        with gr.Blocks(theme=None, css=custom_css, title="Landlord-Tenant Rights Assistant") as demo:
            # --- Header Section: Prominent, dynamic banner ---
            with gr.Group(elem_classes="app-header-wrapper"):
                gr.Markdown(
                    """
                    <div class="app-header">
                        <span class="app-header-logo">⚖️</span>
                        <h1 class="app-header-title">Landlord-Tenant Rights Assistant</h1>
                        <p class="app-header-tagline">Empowering You with State-Specific Legal Insights</p>
                    </div>
                    """
                )

            # --- "Know Your Rights" Section: Informational card ---
            with gr.Group(elem_classes="content-surface"):
                gr.Markdown("<h3 class='section-title'>Know Your Rights</h3>")
                gr.Markdown(
                    """
                    <p>Navigate landlord-tenant laws with ease. Enter your <strong>OpenAI API key</strong>, select your state, and ask your question to get detailed, state-specific answers.</p>
                    <p>Don't have an API key? <a href='https://platform.openai.com/api-keys' target='_blank'>Get one free from OpenAI</a>.</p>
                    <p><strong>Disclaimer:</strong> This tool provides information only, not legal advice. For legal guidance, always consult a licensed attorney.</p>
                    """
                )

            # --- "Ask Your Question" Section (Input Form): Structured and clear inputs ---
            with gr.Group(elem_classes="content-surface input-form-card"):
                gr.Markdown("<h3>Ask Your Question</h3>")
                with gr.Column(elem_classes="input-field-group"):
                    api_key_input = gr.Textbox(
                        label="OpenAI API Key", type="password", placeholder="Enter your API key (e.g., sk-...)",
                        info="Required to process your query. Securely used per request, not stored.", lines=1
                    )
                with gr.Row(elem_classes="input-row"):
                    with gr.Column(elem_classes="input-field", min_width="58%"): # Allocate more width for the question
                        query_input = gr.Textbox(
                            label="Your Question", placeholder="E.g., What are the rules for security deposit returns in my state?",
                            lines=5, max_lines=10
                        )
                    with gr.Column(elem_classes="input-field", min_width="38%"): # Allocate less width for the dropdown
                        state_input = gr.Dropdown(
                            label="Select State", choices=dropdown_choices, value=initial_value,
                            allow_custom_value=False
                        )
                with gr.Row(elem_classes="button-row"):
                    clear_button = gr.Button("Clear", variant="secondary", elem_classes=["gr-button-secondary"])
                    submit_button = gr.Button("Submit Query", variant="primary", elem_classes=["gr-button-primary"])

            # --- Output Section: Clearly formatted answers or messages ---
            with gr.Group(elem_classes="content-surface output-card"):
                output = gr.Markdown(
                    value="<div class='placeholder'>Your answer will appear here after submitting your query.</div>",
                    elem_classes="output-content-wrapper" # This div will be replaced by the answer HTML
                )

            # --- "Explore Sample Questions" Section: Interactive examples ---
            if example_queries:
                with gr.Group(elem_classes="content-surface examples-card"):
                    gr.Examples(
                        examples=example_queries, inputs=[query_input, state_input],
                        label="Explore Sample Questions", examples_per_page=5
                    )
            else:
                with gr.Group(elem_classes="content-surface"):
                    gr.Markdown("<div class='placeholder'>Sample questions could not be loaded.</div>")

            # --- Footer Section: Disclaimer and author info ---
            with gr.Group(elem_classes="app-footer-wrapper"):
                gr.Markdown(
                    """
                    <div class="app-footer">
                        <p>This tool is for informational purposes only and does not constitute legal advice. For legal guidance, always consult with a licensed attorney in your jurisdiction.</p>
                        <p>Developed by <strong>Nischal Subedi</strong>.
                        Connect on <a href="https://www.linkedin.com/in/nischal1/" target='_blank'>LinkedIn</a>
                        or explore insights at <a href="https://datascientistinsights.substack.com/" target='_blank'>Substack</a>.</p>
                    </div>
                    """
                )

            # --- Event Listeners ---
            submit_button.click(
                fn=query_interface_wrapper, inputs=[api_key_input, query_input, state_input], outputs=output, api_name="submit_query"
            )
            clear_button.click(
                fn=lambda: (
                    "", # Clear API key input
                    "", # Clear query input
                    initial_value, # Reset state dropdown to initial value
                    "<div class='placeholder'>Inputs cleared. Ready for your next question.</div>" # Reset output to placeholder
                ),
                inputs=[], outputs=[api_key_input, query_input, state_input, output]
            )
        logging.info("Advanced UI (Legal Lumen theme) Gradio interface created.")
        return demo

# --- Main Execution Block (remains untouched from original logic) ---
if __name__ == "__main__":
    logging.info("Starting Landlord-Tenant Rights Bot application...")
    try:
        SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
        DEFAULT_PDF_PATH = os.path.join(SCRIPT_DIR, "tenant-landlord.pdf")
        DEFAULT_DB_PATH = os.path.join(SCRIPT_DIR, "chroma_db")

        # Use environment variables if set, otherwise default paths
        PDF_PATH = os.getenv("PDF_PATH", DEFAULT_PDF_PATH)
        VECTOR_DB_PATH = os.getenv("VECTOR_DB_PATH", DEFAULT_DB_PATH)

        # Ensure directories exist
        os.makedirs(os.path.dirname(VECTOR_DB_PATH), exist_ok=True)
        # If PDF_PATH could point to a file in a non-existent subdirectory, uncomment:
        # if os.path.dirname(PDF_PATH):
        #     os.makedirs(os.path.dirname(PDF_PATH), exist_ok=True)


        # Validate PDF file existence before proceeding
        if not os.path.exists(PDF_PATH):
            logging.error(f"FATAL: PDF file not found at the specified path: {PDF_PATH}")
            print(f"\n--- CONFIGURATION ERROR ---\nPDF file ('{os.path.basename(PDF_PATH)}') not found at: {PDF_PATH}\nPlease ensure it exists or set 'PDF_PATH' environment variable.\n---------------------------\n")
            exit(1)

        # Initialize Vector Database and RAG System
        vector_db_instance = VectorDatabase(persist_directory=VECTOR_DB_PATH)
        rag = RAGSystem(vector_db=vector_db_instance)
        rag.load_pdf(PDF_PATH) # Load/process PDF data into the vector DB

        # Create and launch the Gradio interface
        app_interface = rag.gradio_interface()
        SERVER_PORT = 7860
        logging.info(f"Launching Gradio app on http://0.0.0.0:{SERVER_PORT}")
        print(f"\n--- Gradio App Running ---\nAccess at: http://localhost:{SERVER_PORT}\n(Share link will be available if you use share=True)\n--------------------------\n")
        app_interface.launch(server_name="0.0.0.0", server_port=SERVER_PORT, share=True)

    except Exception as e:
        logging.error(f"Application startup failed: {str(e)}", exc_info=True)
        print(f"\n--- FATAL STARTUP ERROR ---\n{str(e)}\nCheck logs for more details.\n---------------------------\n")
        exit(1)