File size: 31,299 Bytes
a144435
 
 
7aa591f
56aa65a
7aa591f
a144435
 
 
 
7aa591f
 
 
 
 
 
a144435
7aa591f
a144435
7aa591f
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
a144435
 
7aa591f
a144435
7aa591f
a144435
7aa591f
a144435
 
 
7aa591f
 
a144435
7aa591f
a144435
 
 
7aa591f
 
 
 
 
 
a144435
7aa591f
a144435
7aa591f
a144435
 
7aa591f
a144435
7aa591f
a144435
7aa591f
a144435
7aa591f
 
 
 
 
 
 
56aa65a
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
 
7aa591f
 
a144435
7aa591f
a144435
 
 
7aa591f
 
a144435
7aa591f
a144435
7aa591f
 
56aa65a
7aa591f
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
a144435
 
7aa591f
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
a144435
 
 
 
7aa591f
 
 
a144435
7aa591f
a144435
7aa591f
a144435
7aa591f
a144435
7aa591f
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
 
 
7aa591f
 
 
 
a144435
 
 
 
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
 
7aa591f
 
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
a144435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7aa591f
a144435
7aa591f
a144435
7aa591f
 
 
a144435
7aa591f
 
56aa65a
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
a144435
 
 
 
 
 
 
 
7aa591f
 
 
 
 
 
a144435
7aa591f
a144435
7aa591f
a144435
 
7aa591f
a144435
7aa591f
a144435
7aa591f
 
 
 
 
 
 
a144435
7aa591f
a144435
 
 
 
 
 
 
7aa591f
a144435
7aa591f
a144435
 
 
7aa591f
a144435
 
 
 
 
 
 
 
7aa591f
a144435
7aa591f
a144435
 
7aa591f
a144435
 
7aa591f
a144435
 
 
7aa591f
a144435
 
 
 
 
 
 
 
7aa591f
a144435
 
 
7aa591f
a144435
7aa591f
a144435
7aa591f
a144435
 
 
 
7aa591f
 
 
a144435
 
 
7aa591f
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
a144435
 
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
 
 
7aa591f
 
 
 
a144435
7aa591f
a144435
 
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a144435
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56aa65a
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56aa65a
7aa591f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56aa65a
a144435
 
7aa591f
a144435
34089a0
a144435
 
 
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
import gradio as gr
import json
import os
import pandas as pd
import re
import glob
from typing import Dict, List, Any
from main3 import run_rag_tool_router, execute_diet_tool
from diet_tool import generate_diet_plan, get_diet_recommendations, calculate_nutrition_info

# Ensure outputs directory exists
os.makedirs("outputs", exist_ok=True)

# Global chat history
chat_history = []

def format_json_to_table(json_data: Any, title: str = "") -> str:
    """Convert JSON data to a formatted table string"""
    if not json_data:
        return ""
    
    try:
        if isinstance(json_data, str):
            json_data = json.loads(json_data)
        
        if isinstance(json_data, dict):
            return format_dict_to_table(json_data, title)
        elif isinstance(json_data, list):
            return format_list_to_table(json_data, title)
        else:
            return str(json_data)
    except:
        return str(json_data)

def format_dict_to_table(data: dict, title: str = "") -> str:
    """Format dictionary as a table"""
    if not data:
        return ""
    
    result = f"## {title}\n\n" if title else ""
    
    # Check if it's a simple key-value dict
    if all(not isinstance(v, (dict, list)) for v in data.values()):
        result += "| Key | Value |\n"
        result += "|-----|-------|\n"
        for key, value in data.items():
            result += f"| **{key}** | {value} |\n"
    else:
        # Complex nested structure
        for key, value in data.items():
            if isinstance(value, dict):
                result += f"### {key}\n"
                result += format_dict_to_table(value)
            elif isinstance(value, list):
                result += f"### {key}\n"
                result += format_list_to_table(value)
            else:
                result += f"**{key}**: {value}\n"
    
    return result

def format_list_to_table(data: list, title: str = "") -> str:
    """Format list as a table"""
    if not data:
        return ""
    
    result = f"## {title}\n\n" if title else ""
    
    if not data:
        return result
    
    # Check if all items are dictionaries with similar keys
    if all(isinstance(item, dict) for item in data):
        # Get all unique keys
        all_keys = set()
        for item in data:
            all_keys.update(item.keys())
        
        if all_keys:
            # Create table header
            result += "| " + " | ".join(all_keys) + " |\n"
            result += "|" + "|".join(["---"] * len(all_keys)) + "|\n"
            
            # Add rows
            for item in data:
                row = []
                for key in all_keys:
                    value = item.get(key, "")
                    if isinstance(value, (dict, list)):
                        value = json.dumps(value, ensure_ascii=False)[:50] + "..."
                    row.append(str(value))
                result += "| " + " | ".join(row) + " |\n"
        else:
            result += "Empty list\n"
    else:
        # Simple list
        for i, item in enumerate(data):
            result += f"{i+1}. {item}\n"
    
    return result

def format_diet_plan_result(result: dict) -> str:
    """Format diet plan result specifically"""
    if not result or "error" in result:
        return f"โŒ Error: {result.get('error', 'Unknown error')}"
    
    formatted = "## ๐Ÿฝ๏ธ Diet Plan\n\n"
    
    if "plan_type" in result:
        formatted += f"**Plan Type**: {result['plan_type']}\n\n"
    
    if "plan" in result:
        plan = result["plan"]
        
        # Daily totals
        if "daily_totals" in plan:
            totals = plan["daily_totals"]
            formatted += "### ๐Ÿ“Š Daily Nutrition Summary\n\n"
            formatted += "| Nutrient | Amount |\n"
            formatted += "|----------|--------|\n"
            formatted += f"| **Calories** | {totals.get('calories', 0)} kcal |\n"
            formatted += f"| **Protein** | {totals.get('protein', 0)} g |\n"
            formatted += f"| **Carbs** | {totals.get('carbs', 0)} g |\n"
            formatted += f"| **Fat** | {totals.get('fat', 0)} g |\n"
            formatted += f"| **Fiber** | {totals.get('fiber', 0)} g |\n\n"
        
        # Meals
        if "meals" in plan:
            formatted += "### ๐Ÿฝ๏ธ Meals\n\n"
            for meal in plan["meals"]:
                formatted += f"#### {meal.get('meal_name', 'Meal')} ({meal.get('time_range', '')})\n\n"
                
                # Meal nutrition
                if "nutrition" in meal:
                    nutrition = meal["nutrition"]
                    formatted += "**Nutrition**: "
                    formatted += f"{nutrition.get('calories', 0)} kcal, "
                    formatted += f"{nutrition.get('protein', 0)}g protein, "
                    formatted += f"{nutrition.get('carbs', 0)}g carbs, "
                    formatted += f"{nutrition.get('fat', 0)}g fat\n\n"
                
                # Foods
                if "foods" in meal:
                    formatted += "**Foods**:\n"
                    for food in meal["foods"]:
                        formatted += f"- **{food.get('name', 'Unknown')}** "
                        formatted += f"({food.get('portion_grams', 0)}g) - "
                        formatted += f"{food.get('calories', 0)} kcal\n"
                    formatted += "\n"
    
    elif "plans" in result:
        # Weekly plan
        plans = result["plans"]
        formatted += f"### ๐Ÿ“… Weekly Plan ({len(plans)} days)\n\n"
        
        for i, plan in enumerate(plans):  # Show all days
            formatted += f"#### Day {i+1} - {plan.get('date', '')}\n"
            if "daily_totals" in plan:
                totals = plan["daily_totals"]
                formatted += f"**Total**: {totals.get('calories', 0)} kcal, "
                formatted += f"{totals.get('protein', 0)}g protein\n\n"
    
    return formatted

def format_recommendations_result(result: dict) -> str:
    """Format recommendations result specifically"""
    if not result or "error" in result:
        return f"โŒ Error: {result.get('error', 'Unknown error')}"
    
    formatted = "## ๐Ÿ“Š Diet Recommendations\n\n"
    
    # Basic metrics
    if "bmr" in result:
        formatted += f"**BMR (Basal Metabolic Rate)**: {result['bmr']} kcal/day\n"
    if "tdee" in result:
        formatted += f"**TDEE (Total Daily Energy Expenditure)**: {result['tdee']} kcal/day\n"
    if "target_calories" in result:
        formatted += f"**Target Calories**: {result['target_calories']} kcal/day\n\n"
    
    # Macro ratios
    if "macro_ratios" in result:
        ratios = result["macro_ratios"]
        formatted += "### ๐ŸŽฏ Macro Ratios\n\n"
        formatted += "| Macronutrient | Percentage |\n"
        formatted += "|---------------|------------|\n"
        for macro, ratio in ratios.items():
            formatted += f"| **{macro.title()}** | {ratio} |\n"
        formatted += "\n"
    
    # Macro grams
    if "macro_grams" in result:
        grams = result["macro_grams"]
        formatted += "### โš–๏ธ Daily Macro Targets (grams)\n\n"
        formatted += "| Macronutrient | Grams |\n"
        formatted += "|---------------|-------|\n"
        for macro, grams_val in grams.items():
            formatted += f"| **{macro.title()}** | {grams_val} g |\n"
        formatted += "\n"
    
    # Recommendations
    if "recommendations" in result:
        recs = result["recommendations"]
        formatted += "### ๐Ÿ’ก Recommendations\n\n"
        for key, value in recs.items():
            formatted += f"**{key.replace('_', ' ').title()}**: {value}\n"
    
    return formatted

def format_nutrition_result(result: dict) -> str:
    """Format nutrition calculation result specifically"""
    if not result or "error" in result:
        return f"โŒ Error: {result.get('error', 'Unknown error')}"
    
    formatted = "## ๐Ÿงฎ Nutrition Information\n\n"
    
    if "food_name" in result:
        formatted += f"**Food**: {result['food_name']}\n"
    if "portion_grams" in result:
        formatted += f"**Portion**: {result['portion_grams']} grams\n\n"
    
    # Basic nutrition
    formatted += "### ๐Ÿ“Š Nutritional Values\n\n"
    formatted += "| Nutrient | Amount |\n"
    formatted += "|----------|--------|\n"
    
    nutrients = ["calories", "protein", "carbs", "fat", "fiber"]
    for nutrient in nutrients:
        if nutrient in result:
            unit = "kcal" if nutrient == "calories" else "g"
            formatted += f"| **{nutrient.title()}** | {result[nutrient]} {unit} |\n"
    
    # Vitamins and minerals
    if "vitamins" in result and result["vitamins"]:
        formatted += "\n### ๐Ÿฅ• Vitamins\n\n"
        if isinstance(result["vitamins"], list):
            for vitamin in result["vitamins"]:
                formatted += f"- {vitamin}\n"
        else:
            formatted += str(result["vitamins"])
    
    if "minerals" in result and result["minerals"]:
        formatted += "\n### โšก Minerals\n\n"
        if isinstance(result["minerals"], list):
            for mineral in result["minerals"]:
                formatted += f"- {mineral}\n"
        else:
            formatted += str(result["minerals"])
    
    return formatted

def load_latest_json_output() -> str:
    """Load and format the latest JSON output file"""
    outputs_dir = "outputs"
    if not os.path.exists(outputs_dir):
        return "โŒ No outputs directory found"
    
    # Get all JSON files in outputs directory
    json_files = glob.glob(os.path.join(outputs_dir, "*.json"))
    if not json_files:
        return "โŒ No JSON files found in outputs directory"
    
    # Sort by modification time and get the latest
    latest_file = max(json_files, key=os.path.getmtime)
    
    try:
        with open(latest_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # Extract filename for title
        filename = os.path.basename(latest_file)
        
        # Format based on file type
        if "diet_plan" in filename:
            if "weekly" in filename:
                return format_weekly_diet_plan(data, filename)
            else:
                return format_daily_diet_plan(data, filename)
        elif "recommendations" in filename:
            return format_recommendations_result(data, filename)
        elif "nutrition" in filename:
            return format_nutrition_result(data, filename)
        else:
            return format_json_data_to_table(data, f"Latest Output: {filename}")
            
    except Exception as e:
        return f"โŒ Error reading {latest_file}: {str(e)}"

def format_weekly_diet_plan(data: dict, filename: str) -> str:
    """Format weekly diet plan from JSON file"""
    if not data or "result" not in data:
        return f"โŒ Invalid data in {filename}"
    
    result = data["result"]
    if "plans" not in result:
        return f"โŒ No plans found in {filename}"
    
    plans = result["plans"]
    formatted = f"## ๐Ÿ“… Weekly Diet Plan ({len(plans)} days)\n\n"
    formatted += f"**File**: {filename}\n\n"
    
    # Summary table for all days
    formatted += "### ๐Ÿ“Š Weekly Summary\n\n"
    formatted += "| Day | Date | Calories | Protein | Carbs | Fat | Fiber |\n"
    formatted += "|-----|------|----------|---------|-------|-----|-------|\n"
    
    for i, plan in enumerate(plans):
        totals = plan.get("daily_totals", {})
        date = plan.get("date", f"Day {i+1}")
        formatted += f"| {i+1} | {date} | {totals.get('calories', 0)} | {totals.get('protein', 0)}g | {totals.get('carbs', 0)}g | {totals.get('fat', 0)}g | {totals.get('fiber', 0)}g |\n"
    
    # Detailed view for all days
    formatted += "\n### ๐Ÿฝ๏ธ Detailed Meals (All Days)\n\n"
    
    for i, plan in enumerate(plans):
        date = plan.get("date", f"Day {i+1}")
        formatted += f"#### Day {i+1} - {date}\n\n"
        
        meals = plan.get("meals", [])
        for meal in meals:
            meal_name = meal.get("meal_name", "Meal")
            time_range = meal.get("time_range", "")
            nutrition = meal.get("nutrition", {})
            
            formatted += f"**{meal_name}** ({time_range})\n"
            formatted += f"- Calories: {nutrition.get('calories', 0)} | Protein: {nutrition.get('protein', 0)}g | Carbs: {nutrition.get('carbs', 0)}g | Fat: {nutrition.get('fat', 0)}g\n"
            
            # Foods
            foods = meal.get("foods", [])
            if foods:
                formatted += "  - Foods: "
                food_names = [f.get("name", "Unknown") for f in foods[:3]]  # Show first 3 foods
                formatted += ", ".join(food_names)
                if len(foods) > 3:
                    formatted += f" (+{len(foods)-3} more)"
                formatted += "\n"
            formatted += "\n"
    
    return formatted

def format_daily_diet_plan(data: dict, filename: str) -> str:
    """Format daily diet plan from JSON file"""
    if not data or "result" not in data:
        return f"โŒ Invalid data in {filename}"
    
    result = data["result"]
    if "plan" not in result:
        return f"โŒ No plan found in {filename}"
    
    plan = result["plan"]
    formatted = f"## ๐Ÿฝ๏ธ Daily Diet Plan\n\n"
    formatted += f"**File**: {filename}\n\n"
    
    # Daily totals
    if "daily_totals" in plan:
        totals = plan["daily_totals"]
        formatted += "### ๐Ÿ“Š Daily Nutrition Summary\n\n"
        formatted += "| Nutrient | Amount |\n"
        formatted += "|----------|--------|\n"
        formatted += f"| **Calories** | {totals.get('calories', 0)} kcal |\n"
        formatted += f"| **Protein** | {totals.get('protein', 0)} g |\n"
        formatted += f"| **Carbs** | {totals.get('carbs', 0)} g |\n"
        formatted += f"| **Fat** | {totals.get('fat', 0)} g |\n"
        formatted += f"| **Fiber** | {totals.get('fiber', 0)} g |\n\n"
    
    # Meals
    if "meals" in plan:
        formatted += "### ๐Ÿฝ๏ธ Meals\n\n"
        for meal in plan["meals"]:
            meal_name = meal.get("meal_name", "Meal")
            time_range = meal.get("time_range", "")
            nutrition = meal.get("nutrition", {})
            
            formatted += f"#### {meal_name} ({time_range})\n\n"
            formatted += f"**Nutrition**: {nutrition.get('calories', 0)} kcal, {nutrition.get('protein', 0)}g protein, {nutrition.get('carbs', 0)}g carbs, {nutrition.get('fat', 0)}g fat\n\n"
            
            # Foods
            foods = meal.get("foods", [])
            if foods:
                formatted += "**Foods**:\n"
                for food in foods:
                    name = food.get("name", "Unknown")
                    portion = food.get("portion_grams", 0)
                    calories = food.get("calories", 0)
                    formatted += f"- **{name}** ({portion}g) - {calories} kcal\n"
                formatted += "\n"
    
    return formatted

def list_all_json_outputs() -> str:
    """List all JSON output files with their details"""
    outputs_dir = "outputs"
    if not os.path.exists(outputs_dir):
        return "โŒ No outputs directory found"
    
    json_files = glob.glob(os.path.join(outputs_dir, "*.json"))
    if not json_files:
        return "โŒ No JSON files found in outputs directory"
    
    # Sort by modification time (newest first)
    json_files.sort(key=os.path.getmtime, reverse=True)
    
    formatted = "## ๐Ÿ“ Available JSON Outputs\n\n"
    formatted += "| File | Type | Size | Modified |\n"
    formatted += "|------|------|------|----------|\n"
    
    for file_path in json_files:
        filename = os.path.basename(file_path)
        file_type = "Unknown"
        
        if "diet_plan_weekly" in filename:
            file_type = "Weekly Diet Plan"
        elif "diet_plan_daily" in filename:
            file_type = "Daily Diet Plan"
        elif "recommendations" in filename:
            file_type = "Recommendations"
        elif "nutrition" in filename:
            file_type = "Nutrition Info"
        
        file_size = os.path.getsize(file_path)
        mod_time = os.path.getmtime(file_path)
        mod_date = pd.Timestamp.fromtimestamp(mod_time).strftime("%Y-%m-%d %H:%M")
        
        formatted += f"| {filename} | {file_type} | {file_size:,} bytes | {mod_date} |\n"
    
    return formatted

def extract_and_format_json_in_text(text: str) -> str:
    """Extract JSON objects from text and format them as tables"""
    if not text:
        return text
    
    formatted_text = text
    
    # First, try to find JSON in code blocks
    code_block_pattern = r'```(?:json)?\s*(\{.*?\})\s*```'
    matches = list(re.finditer(code_block_pattern, formatted_text, re.DOTALL | re.IGNORECASE))
    
    for match in reversed(matches):
        json_str = match.group(1).strip()
        try:
            json_data = json.loads(json_str)
            table = format_json_data_to_table(json_data)
            formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
        except:
            continue
    
    # Then, try to find standalone JSON objects
    # Look for patterns that start with { and end with }
    json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
    matches = list(re.finditer(json_pattern, formatted_text, re.DOTALL))
    
    for match in reversed(matches):
        json_str = match.group(0).strip()
        
        # Skip if it's already been processed or is too short
        if len(json_str) < 10 or '|' in json_str:
            continue
            
        try:
            json_data = json.loads(json_str)
            # Only format if it looks like structured data
            if isinstance(json_data, (dict, list)) and len(str(json_data)) > 20:
                table = format_json_data_to_table(json_data)
                formatted_text = formatted_text[:match.start()] + table + formatted_text[match.end():]
        except:
            continue
    
    return formatted_text

def format_json_data_to_table(json_data: Any) -> str:
    """Format JSON data to a table string"""
    if isinstance(json_data, dict):
        return format_dict_to_table(json_data, "Data")
    elif isinstance(json_data, list):
        return format_list_to_table(json_data, "Data")
    else:
        return str(json_data)

def process_user_input(user_input: str, history: List) -> tuple:
    """Process user input through RAG system"""
    global chat_history
    
    if not user_input.strip():
        return history, ""
    
    # Convert Gradio history format to our format
    rag_history = []
    for msg in history:
        if isinstance(msg, dict):
            rag_history.append(msg)
        else:
            # Handle old format
            user_msg, bot_msg = msg
            rag_history.append({"role": "user", "content": user_msg})
            rag_history.append({"role": "assistant", "content": bot_msg})
    
    # Process through RAG system
    result = run_rag_tool_router(user_input, rag_history)
    
    # Update our chat history
    chat_history.append({"role": "user", "content": user_input})
    
    # Handle different response types
    if isinstance(result, dict) and "final" in result:
        response = result["final"]
        # Format any JSON in the response
        formatted_response = extract_and_format_json_in_text(response)
        chat_history.append({"role": "assistant", "content": formatted_response})
        history.append({"role": "user", "content": user_input})
        history.append({"role": "assistant", "content": formatted_response})
        return history, ""
    
    elif isinstance(result, dict) and "action" in result:
        action = result["action"]
        args = result.get("args", {})
        
        # Show the action being taken
        action_response = f"**Executing**: {action}\n\n**Arguments**:\n```json\n{json.dumps(args, indent=2)}\n```"
        
        # Execute diet tools
        if action in ["generate_diet_plan", "get_diet_recommendations", "calculate_nutrition_info", "expand_diet_database"]:
            diet_result = execute_diet_tool(action, args)
            
            if diet_result.get("success"):
                final_response = f"โœ… **{diet_result.get('message', 'Operation completed successfully')}**\n\n"
                if "result" in diet_result:
                    # Format the result based on action type
                    if action == "generate_diet_plan":
                        formatted_result = format_diet_plan_result(diet_result['result'])
                    elif action == "get_diet_recommendations":
                        formatted_result = format_recommendations_result(diet_result['result'])
                    elif action == "calculate_nutrition_info":
                        formatted_result = format_nutrition_result(diet_result['result'])
                    else:
                        formatted_result = format_json_to_table(diet_result['result'], "Result")
                    
                    final_response += formatted_result
            else:
                final_response = f"โŒ **Error**: {diet_result.get('error', 'Unknown error occurred')}"
            
            # Add to history
            history.append({"role": "user", "content": user_input})
            history.append({"role": "assistant", "content": action_response + "\n\n" + final_response})
            chat_history.append({"role": "assistant", "content": final_response})
        else:
            # For other tools, show placeholder
            final_response = "๐Ÿ”„ This tool is not yet implemented in the web interface."
            history.append({"role": "user", "content": user_input})
            history.append({"role": "assistant", "content": action_response + "\n\n" + final_response})
            chat_history.append({"role": "assistant", "content": final_response})
        
        return history, ""
    
    else:
        # Handle errors or other responses
        error_response = f"โŒ **Error**: {json.dumps(result, indent=2, ensure_ascii=False)}"
        chat_history.append({"role": "assistant", "content": error_response})
        history.append({"role": "user", "content": user_input})
        history.append({"role": "assistant", "content": error_response})
        return history, ""

def create_diet_plan_interface(age: int, sex: str, height_cm: float, weight_kg: float, 
                              activity_level: str, goal: str, plan_type: str) -> str:
    """Create diet plan using the interface"""
    user_profile = {
        "age": age,
        "sex": sex,
        "height_cm": height_cm,
        "weight_kg": weight_kg,
        "activity_level": activity_level,
        "goal": goal,
        "dietary_restrictions": [],
        "allergies": [],
        "preferences": []
    }
    
    try:
        result = generate_diet_plan(user_profile, plan_type)
        return format_diet_plan_result(result)
    except Exception as e:
        return f"โŒ Error: {str(e)}"

def get_recommendations_interface(age: int, sex: str, height_cm: float, weight_kg: float, 
                                 activity_level: str, goal: str) -> str:
    """Get diet recommendations using the interface"""
    user_profile = {
        "age": age,
        "sex": sex,
        "height_cm": height_cm,
        "weight_kg": weight_kg,
        "activity_level": activity_level,
        "goal": goal,
        "dietary_restrictions": [],
        "allergies": [],
        "preferences": []
    }
    
    try:
        result = get_diet_recommendations(user_profile)
        return format_recommendations_result(result)
    except Exception as e:
        return f"โŒ Error: {str(e)}"

def calculate_nutrition_interface(food_name: str, portion_grams: float) -> str:
    """Calculate nutrition info using the interface"""
    try:
        result = calculate_nutrition_info(food_name, portion_grams)
        return format_nutrition_result(result)
    except Exception as e:
        return f"โŒ Error: {str(e)}"

# Create Gradio interface
with gr.Blocks(title="RAG Diet Assistant") as app:
    gr.Markdown("# ๐Ÿฝ๏ธ RAG Diet Assistant")
    gr.Markdown("Your intelligent nutrition planning assistant powered by RAG (Retrieval-Augmented Generation)")
    
    with gr.Tabs():
        # Chat Interface Tab
        with gr.Tab("๐Ÿ’ฌ Chat Assistant"):
            gr.Markdown("Ask me anything about diet planning, nutrition, or health!")
            
            chatbot = gr.Chatbot(
                label="Conversation",
                height=500,
                type="messages",
                render_markdown=True
            )
            
            with gr.Row():
                msg = gr.Textbox(
                    label="Your message",
                    placeholder="Ask me to create a diet plan, calculate nutrition, or get recommendations...",
                    lines=2,
                    scale=4
                )
                send_btn = gr.Button("Send", variant="primary", scale=1)
            
            # Action buttons
            with gr.Row():
                clear_btn = gr.Button("Clear Chat", variant="secondary")
                load_latest_btn = gr.Button("๐Ÿ“„ Load Latest JSON", variant="secondary")
                list_outputs_btn = gr.Button("๐Ÿ“ List All Outputs", variant="secondary")
            
            # Event handlers
            msg.submit(process_user_input, [msg, chatbot], [chatbot, msg])
            send_btn.click(process_user_input, [msg, chatbot], [chatbot, msg])
            clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
            load_latest_btn.click(lambda: ([{"role": "assistant", "content": load_latest_json_output()}], ""), outputs=[chatbot, msg])
            list_outputs_btn.click(lambda: ([{"role": "assistant", "content": list_all_json_outputs()}], ""), outputs=[chatbot, msg])
        
        # Diet Plan Creator Tab
        with gr.Tab("๐Ÿ“‹ Diet Plan Creator"):
            gr.Markdown("Create personalized diet plans based on your profile")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Personal Information")
                    age = gr.Number(label="Age", value=30, minimum=15, maximum=100)
                    sex = gr.Dropdown(label="Gender", choices=["male", "female"], value="male")
                    height_cm = gr.Number(label="Height (cm)", value=175, minimum=100, maximum=250)
                    weight_kg = gr.Number(label="Weight (kg)", value=75, minimum=30, maximum=300)
                    
                    gr.Markdown("### Activity & Goals")
                    activity_level = gr.Dropdown(
                        label="Activity Level",
                        choices=["sedentary", "light", "moderate", "active", "very_active"],
                        value="moderate"
                    )
                    goal = gr.Dropdown(
                        label="Goal",
                        choices=["weight_loss", "muscle_gain", "maintenance", "keto", "mediterranean"],
                        value="weight_loss"
                    )
                    plan_type = gr.Dropdown(
                        label="Plan Type",
                        choices=["daily", "weekly"],
                        value="daily"
                    )
                    
                    create_plan_btn = gr.Button("Create Diet Plan", variant="primary")
                
                with gr.Column():
                    plan_output = gr.Textbox(
                        label="Diet Plan",
                        lines=20,
                        max_lines=30
                    )
            
            create_plan_btn.click(
                create_diet_plan_interface,
                inputs=[age, sex, height_cm, weight_kg, activity_level, goal, plan_type],
                outputs=plan_output
            )
        
        # Recommendations Tab
        with gr.Tab("๐Ÿ“Š Diet Recommendations"):
            gr.Markdown("Get personalized nutrition recommendations")
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Personal Information")
                    rec_age = gr.Number(label="Age", value=30, minimum=15, maximum=100)
                    rec_sex = gr.Dropdown(label="Gender", choices=["male", "female"], value="male")
                    rec_height_cm = gr.Number(label="Height (cm)", value=175, minimum=100, maximum=250)
                    rec_weight_kg = gr.Number(label="Weight (kg)", value=75, minimum=30, maximum=300)
                    
                    gr.Markdown("### Activity & Goals")
                    rec_activity_level = gr.Dropdown(
                        label="Activity Level",
                        choices=["sedentary", "light", "moderate", "active", "very_active"],
                        value="moderate"
                    )
                    rec_goal = gr.Dropdown(
                        label="Goal",
                        choices=["weight_loss", "muscle_gain", "maintenance", "keto", "mediterranean"],
                        value="weight_loss"
                    )
                    
                    get_rec_btn = gr.Button("Get Recommendations", variant="primary")
                
                with gr.Column():
                    rec_output = gr.Textbox(
                        label="Recommendations",
                        lines=15,
                        max_lines=20
                    )
            
            get_rec_btn.click(
                get_recommendations_interface,
                inputs=[rec_age, rec_sex, rec_height_cm, rec_weight_kg, rec_activity_level, rec_goal],
                outputs=rec_output
            )
        
        # Nutrition Calculator Tab
        with gr.Tab("๐Ÿงฎ Nutrition Calculator"):
            gr.Markdown("Calculate nutritional values for specific foods")
            
            with gr.Row():
                with gr.Column():
                    food_name = gr.Textbox(
                        label="Food Name",
                        placeholder="e.g., Chicken Breast, Apple, Brown Rice...",
                        value="Chicken Breast"
                    )
                    portion_grams = gr.Number(
                        label="Portion (grams)",
                        value=150,
                        minimum=1,
                        maximum=1000
                    )
                    
                    calc_nutrition_btn = gr.Button("Calculate Nutrition", variant="primary")
                
                with gr.Column():
                    nutrition_output = gr.Textbox(
                        label="Nutritional Information",
                        lines=15,
                        max_lines=20
                    )
            
            calc_nutrition_btn.click(
                calculate_nutrition_interface,
                inputs=[food_name, portion_grams],
                outputs=nutrition_output
            )

def create_gradio_interface():
    """Create and return the Gradio interface for Hugging Face Spaces"""
    return app

if __name__ == "__main__":
    # For local development
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )