#!/usr/bin/env python3
"""
K-Dense Step 4: Report Generation
Generate a comprehensive Markdown report synthesizing the 7-day vegetarian diet plan
with methodology, meal plan, and visual analysis.
"""

import pandas as pd
from pathlib import Path
import sys

# Set base paths
BASE_DIR = Path("/app/sandbox/session_20251221_093619_3390c5c3bed6")
RESULTS_DIR = BASE_DIR / "results"
FIGURES_DIR = BASE_DIR / "figures"
REPORTS_DIR = BASE_DIR / "reports"

# Ensure reports directory exists
REPORTS_DIR.mkdir(exist_ok=True)

def load_data():
    """Load meal plan and daily nutrition summary data."""
    print("Loading data files...")

    meal_plan = pd.read_csv(RESULTS_DIR / "seven_day_meal_plan.csv")
    daily_summary = pd.read_csv(RESULTS_DIR / "daily_nutrition_summary.csv")

    print(f"✓ Loaded meal plan: {meal_plan.shape[0]} meals across {meal_plan['Day'].nunique()} days")
    print(f"✓ Loaded daily summary: {daily_summary.shape[0]} days")

    return meal_plan, daily_summary

def format_meal_plan_table(meal_plan):
    """Format the 7-day meal plan as a Markdown table."""
    print("Formatting meal plan table...")

    # Pivot data to get one row per day with columns for each meal
    table_rows = []

    for day in sorted(meal_plan['Day'].unique()):
        day_meals = meal_plan[meal_plan['Day'] == day]

        row = {"Day": f"Day {day}"}
        total_cals = 0

        for _, meal_row in day_meals.iterrows():
            meal_type = meal_row['Meal']
            dishes = meal_row['Dishes']
            cals = meal_row['Meal_Calories']
            region = meal_row['Main_Region']

            # Format: Dishes (Region) - XXX kcal
            row[meal_type] = f"{dishes}<br>*{region}* ({cals:.0f} kcal)"
            total_cals += cals

        row["Daily Total"] = f"{total_cals:.0f} kcal"
        table_rows.append(row)

    # Convert to DataFrame for easy table generation
    table_df = pd.DataFrame(table_rows)

    # Reorder columns
    col_order = ["Day", "Breakfast", "Lunch", "Snack", "Dinner", "Daily Total"]
    table_df = table_df[col_order]

    # Convert to Markdown table
    md_table = table_df.to_markdown(index=False)

    print(f"✓ Generated table with {len(table_rows)} days")
    return md_table

def calculate_weekly_stats(daily_summary):
    """Calculate weekly aggregate statistics."""
    stats = {
        'avg_calories': daily_summary['Calories'].mean(),
        'avg_protein': daily_summary['Protein'].mean(),
        'avg_carbs': daily_summary['Carbs'].mean(),
        'avg_fats': daily_summary['Fats'].mean(),
        'avg_fiber': daily_summary['Fiber'].mean(),
        'days_within_calorie_target': daily_summary['Within_Calorie_Target'].value_counts().get('Yes', 0),
        'days_meets_protein': daily_summary['Meets_Protein_Min'].value_counts().get('Yes', 0)
    }
    return stats

def generate_report(meal_plan, daily_summary):
    """Generate the complete Markdown report."""
    print("Generating report content...")

    # Calculate statistics
    stats = calculate_weekly_stats(daily_summary)

    # Format meal plan table
    meal_table = format_meal_plan_table(meal_plan)

    # Count regional representation
    region_counts = meal_plan.groupby('Main_Region').size()

    # Build the report content
    report = f"""# 7-Day India-Specific Vegetarian Diet Plan
*A Balanced, Regionally Diverse Meal Plan Based on ICMR-NIN Nutritional Guidelines*

---

## 1. Introduction

This report presents a comprehensive 7-day vegetarian diet plan specifically designed for the Indian population. The plan emphasizes:

- **Regional Diversity**: Incorporates traditional dishes from North, South, East, and West India
- **Nutritional Balance**: Targets approximately 2000 kcal/day with adequate protein (≥50g/day)
- **Cultural Authenticity**: Features authentic Indian vegetarian cuisine
- **Practical Feasibility**: Uses commonly available ingredients and traditional cooking methods

The diet plan is grounded in nutritional data from the Indian Council of Medical Research - National Institute of Nutrition (ICMR-NIN), ensuring that recommendations align with Indian dietary patterns and nutritional requirements.

---

## 2. Methodology

### 2.1 Data Source
The nutritional values for all dishes are based on the **ICMR-NIN Indian Food Composition Tables**, which provide comprehensive macronutrient and micronutrient data for traditional Indian foods. This ensures accuracy and cultural relevance.

### 2.2 Optimization Approach
The meal plan was designed using a multi-criteria optimization approach:

1. **Caloric Balance**: Target daily intake of 1800-2200 kcal to meet adult energy requirements
2. **Protein Adequacy**: Minimum 50g protein per day, with emphasis on complementary protein sources (legumes + grains)
3. **Regional Diversity**: Balanced representation across India's four main culinary regions:
   - North India: {region_counts.get('North', 0)} meals
   - South India: {region_counts.get('South', 0)} meals
   - East India: {region_counts.get('East', 0)} meals
   - West India: {region_counts.get('West', 0)} meals
4. **Meal Structure**: Four meals per day (Breakfast, Lunch, Snack, Dinner) to distribute caloric intake
5. **Variety**: Minimized repetition while maintaining nutritional consistency

---

## 3. Seven-Day Meal Plan

{meal_table}

**Table 1**: Complete 7-day meal plan showing breakfast, lunch, snack, and dinner options with regional origins and caloric values. Each meal showcases traditional Indian vegetarian dishes from different regions.

---

## 4. Nutritional Analysis

### 4.1 Macronutrient Distribution

![Figure 1: Macronutrient Distribution](../figures/01_macro_distribution.png)

**Figure 1**: Overall macronutrient distribution across the 7-day diet plan. The diet maintains a balanced macronutrient profile with:
- **Carbohydrates**: {stats['avg_carbs']:.1f}g/day (primary energy source from rice, wheat, and legumes)
- **Protein**: {stats['avg_protein']:.1f}g/day (from dairy, legumes, and grains)
- **Fats**: {stats['avg_fats']:.1f}g/day (from cooking oils, nuts, and dairy)
- **Fiber**: {stats['avg_fiber']:.1f}g/day (from whole grains, vegetables, and legumes)

This distribution aligns with ICMR recommendations for a balanced vegetarian diet, with carbohydrates providing the majority of energy while ensuring adequate protein from plant and dairy sources.

### 4.2 Daily Caloric Distribution by Meal

![Figure 2: Calories Per Meal Type](../figures/02_calories_per_meal.png)

**Figure 2**: Caloric contribution by meal type across the week. Dinner consistently provides the largest caloric portion (avg ~650-750 kcal), followed by lunch (avg ~550-620 kcal), reflecting traditional Indian eating patterns where the evening meal is typically the most substantial. Breakfast provides a moderate start (avg ~330-440 kcal), while snacks contribute ~300-575 kcal to meet daily energy needs.

### 4.3 Daily Macronutrient Trends

![Figure 3: Daily Macronutrient Composition](../figures/03_daily_macros.png)

**Figure 3**: Day-by-day breakdown of macronutrient intake. The stacked bar chart illustrates consistent macronutrient composition across all seven days, with carbohydrates forming the base (~290-326g/day), followed by fats (~48-75g/day) and protein (~48-64g/day). The 2000 kcal reference line shows that {stats['days_within_calorie_target']} out of 7 days fall within the target caloric range (1800-2200 kcal).

### 4.4 Regional Diversity

![Figure 4: Regional Meal Distribution](../figures/04_regional_diversity.png)

**Figure 4**: Distribution of meals across India's four culinary regions. The diet plan achieves balanced regional representation:
- **North India** ({region_counts.get('North', 0)} meals): Features wheat-based dishes (parathas, rotis), rich curries (paneer-based), and dairy
- **South India** ({region_counts.get('South', 0)} meals): Emphasizes rice, lentils (sambar), fermented foods (idli, dosa), and coconut
- **East India** ({region_counts.get('East', 0)} meals): Showcases bengali cuisine with luchi, dhokar dalna, and mustard oil-based preparations
- **West India** ({region_counts.get('West', 0)} meals): Incorporates gujarati/maharashtrian dishes like thepla, dal dhokli, and bharli vangi

This diversity ensures exposure to varied nutrient profiles and culinary traditions while maintaining overall nutritional balance.

### 4.5 RDA Compliance

![Figure 5: Nutritional Adequacy vs RDA Targets](../figures/05_rda_radar_chart.png)

**Figure 5**: Radar chart comparing daily average nutritional values against Recommended Dietary Allowances (RDA). The diet achieves:
- **Calories**: {stats['avg_calories']:.0f} kcal/day (target: 2000 kcal) - {(stats['avg_calories']/2000*100):.1f}% of target
- **Protein**: {stats['avg_protein']:.1f}g/day (minimum: 50g) - {(stats['avg_protein']/50*100):.1f}% of minimum requirement
- **Carbohydrates**: {stats['avg_carbs']:.1f}g/day (target: 275g) - {(stats['avg_carbs']/275*100):.1f}% of target
- **Fats**: {stats['avg_fats']:.1f}g/day (target: 65g) - {(stats['avg_fats']/65*100):.1f}% of target
- **Fiber**: {stats['avg_fiber']:.1f}g/day (target: 25g) - {(stats['avg_fiber']/25*100):.1f}% of target

The plan successfully meets or exceeds protein requirements on {stats['days_meets_protein']} out of 7 days, demonstrating the adequacy of vegetarian protein sources when properly combined.

---

## 5. Key Findings and Benefits

### 5.1 Nutritional Adequacy
- **Average daily intake**: {stats['avg_calories']:.0f} kcal, closely aligned with the 2000 kcal target
- **Protein sufficiency**: Achieves {stats['avg_protein']:.1f}g protein/day through strategic combination of legumes, dairy, and grains
- **Micronutrient density**: High fiber intake ({stats['avg_fiber']:.1f}g/day) supports digestive health and chronic disease prevention

### 5.2 Cultural Relevance
- Incorporates authentic regional dishes that are familiar and acceptable to Indian populations
- Respects traditional meal patterns and cooking methods
- Promotes dietary diversity and food security by using locally available ingredients

### 5.3 Sustainability and Practicality
- **Plant-based focus**: Environmentally sustainable with lower carbon footprint than meat-based diets
- **Affordable**: Uses staple foods (rice, wheat, lentils, vegetables) accessible across economic strata
- **Scalable**: Can be adapted for institutional feeding programs or public health interventions

---

## 6. Recommendations and Considerations

### 6.1 Individual Adjustments
While this plan provides a solid foundation, individuals should adjust portions and meal compositions based on:
- Age, sex, and physical activity level
- Pre-existing health conditions (diabetes, hypertension, etc.)
- Personal food preferences and allergies
- Seasonal availability of ingredients

### 6.2 Complementary Practices
To maximize nutritional benefits:
- Ensure adequate hydration (8-10 glasses of water daily)
- Include seasonal fruits as desserts or mid-meal snacks
- Consider fortified foods or supplements for vitamin B12 (often limited in vegetarian diets)
- Practice portion control and mindful eating

### 6.3 Future Enhancements
Potential improvements to this diet plan could include:
- Micronutrient analysis (iron, calcium, vitamin D, B12)
- Glycemic index considerations for diabetes management
- Recipe standardization with detailed cooking instructions
- Cost analysis and budget-friendly alternatives

---

## 7. Conclusion

This 7-day vegetarian diet plan demonstrates that it is entirely feasible to meet adult nutritional requirements through a diverse, culturally appropriate Indian vegetarian diet. By drawing from all four major culinary regions of India, the plan offers variety while maintaining consistent nutritional quality across the week.

The analysis confirms that:
1. **Caloric targets are achievable**: {stats['days_within_calorie_target']}/7 days fall within the recommended 1800-2200 kcal range
2. **Protein adequacy is maintained**: Average {stats['avg_protein']:.1f}g/day exceeds the 50g minimum, with {stats['days_meets_protein']}/7 days meeting the threshold
3. **Regional diversity is preserved**: Balanced representation from North, South, East, and West Indian cuisines
4. **Traditional foods are sufficient**: No need for exotic ingredients or supplements for macronutrient adequacy

This plan serves as a practical template for individuals, nutritionists, and public health practitioners seeking to promote healthy vegetarian eating patterns rooted in Indian food traditions. It validates that India's rich culinary heritage, when properly leveraged, provides a strong foundation for nutritional well-being.

---

## 8. Data Sources and Appendices

### Data Sources
- **ICMR-NIN Indian Food Composition Tables** (2017)
- **Recommended Dietary Allowances for Indians** (ICMR, 2020)

### Generated Artifacts
- Meal plan data: `results/seven_day_meal_plan.csv`
- Daily summary: `results/daily_nutrition_summary.csv`
- Figures: `figures/01-05_*.png`
- Analysis scripts: `workflow/01-04_*.py`

---

*Report generated by K-Dense (DendroForge) System*
*Date: 2025-12-21*
"""

    print("✓ Report content generated")
    return report

def save_report(report_content):
    """Save the report to the reports directory."""
    output_path = REPORTS_DIR / "final_diet_plan_report.md"

    print(f"Saving report to {output_path}...")
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(report_content)

    print(f"✓ Report saved successfully: {output_path}")
    print(f"✓ Report size: {len(report_content)} characters")

    return output_path

def main():
    """Main execution function."""
    print("="*60)
    print("K-Dense Step 4: Report Generation")
    print("="*60)
    print()

    try:
        # Load data
        meal_plan, daily_summary = load_data()
        print()

        # Generate report
        report_content = generate_report(meal_plan, daily_summary)
        print()

        # Save report
        output_path = save_report(report_content)
        print()

        print("="*60)
        print("✓ Report generation completed successfully!")
        print("="*60)
        print(f"\nFinal report: {output_path}")
        print(f"Total sections: 8 (Introduction, Methodology, Meal Plan, Analysis, Findings, Recommendations, Conclusion, Appendices)")
        print(f"Embedded figures: 5")
        print(f"Data tables: 1 (7-day meal plan)")

        return 0

    except Exception as e:
        print(f"\n❌ Error during report generation: {e}", file=sys.stderr)
        import traceback
        traceback.print_exc()
        return 1

if __name__ == "__main__":
    sys.exit(main())
