from groq_module import groq_module_fun, chat_with_groq
from helpers import jpeg_to_base64, extract_json_to_dict
from flask import Flask, request, jsonify
import json
import os

app = Flask(__name__)

@app.route('/recipe-maker', methods=['POST'])
def recipe_maker():
    data = request.get_json()
    if not data:
        return jsonify({"error": "JSON body is required"}), 400

    query = data.get('query')


    prompt = f''' based on the following query:
    query: {query}
    generate the recipe of the best 5 dishes in the following JSON format:
    

    {{
        "message": "<message response>"
        "Recipe":{{
            "dish1": {{
                "name": "<dish name>",
                "ingredients": "<dish ingredients>",
                "instructions": "<dish instructions>"
            }},
            "dish2": {{
                "name": "<dish name>",
                "ingredients": "<dish ingredients>",
                "instructions": "<dish instructions>"
            }},
            "dish3": {{
                "name": "<dish name>",
                "ingredients": "<dish ingredients>",
                "instructions": "<dish instructions>"
            }},
            "dish4": {{
                "name": "<dish name>",
                "ingredients": "<dish ingredients>",
                "instructions": "<dish instructions>"
            }},
            "dish5": {{
                "name": "<dish name>",
                "ingredients": "<dish ingredients>",
                "instructions": "<dish instructions>"
            }}
        }}
        
    }}
    '''

    response = chat_with_groq(prompt)
    print(response)
    recipe = extract_json_to_dict(response)

    

    result = {
        "recipe": recipe,
        "query": query,
    }

    return jsonify(result), 200

@app.route('/diet-plan', methods=['POST'])
def meal_diet_plan():
    data = request.get_json()
    if not data:
        return jsonify({"error": "JSON body is required"}), 400

    weight = data.get('weight')
    height = data.get('height')
    target_weight = data.get('target_weight')

    if weight is None or height is None or target_weight is None:
        return jsonify({"error": "Weight, height, and target weight are required"}), 400

    prompt = f''' based on the following information:
    weight: {weight}
    height: {height}
    target weight: {target_weight}

    Please provide a weekly diet plan for the user to achieve their target weight in the following JSON format:
    {{
        "day1": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day2": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day3": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day4": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day5": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day6": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }},
        "day7": {{
            "breakfast": "<food item>",
            "lunch": "<food item>",
            "snack": "<food item>",
            "dinner": "<food item>"
        }}
    }}
    '''

    response = chat_with_groq(prompt)
    print(response)
    week_diet_plan = extract_json_to_dict(response)

    

    result = {
        "meal_diet_plan": week_diet_plan,
        "weight": weight,
        "height": height,
        "target_weight": target_weight,
    }

    return jsonify(result), 200

@app.route('/food-scan', methods=['POST'])
def food_scan():
    if 'file' not in request.files:
        return jsonify({"error": "File is required"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "Invalid file"}), 400

    # Secure file saving
    temp_dir = "/tmp"
    os.makedirs(temp_dir, exist_ok=True)  # Ensure temp directory exists
    jpeg_file_path = os.path.join(temp_dir, file.filename)
    
    try:
        file.save(jpeg_file_path)
    except Exception as e:
        return jsonify({"error": f"Failed to save file: {str(e)}"}), 500

    # Convert image to Base64
    base64_string = jpeg_to_base64(jpeg_file_path)
    if not base64_string:
        return jsonify({"error": "Failed to encode image"}), 500

    # Construct prompt correctly
    prompt = """
    This is a food image. Classify the food name and category in the following JSON format:
    {
        "food_name": "<detected food name>",
        "category": "<food category>",
        "calories": <calories in food>,
        "fat": <fat in food>,
        "carbohydrates": <carbohydrates in food>,
        "protein": <protein in food>,
        "sugar": <sugar in food>,
        "fiber": <fiber in food>
    }
    """

    # Call the function (ensure this is implemented correctly)
    response = groq_module_fun(prompt, base64_string)
    food_data = json.loads(response)
    result = {
        "result": food_data
    }
    
    return jsonify(result), 200


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8674, debug=True)

