import os
from django.shortcuts import render
from ai.local_ai_api import LocalAIApi
import logging

logger = logging.getLogger(__name__)

def index(request):
    """
    Render the Baymax Healthcare Companion landing page and handle the symptom checker form.
    """
    context = {
        "project_name": "Baymax Healthcare Companion",
        "project_description": "An AI-assisted non-invasive health assistant for symptom triage.",
    }
    ai_result = None

    if request.method == "POST":
        symptoms = request.POST.get("symptoms", "").strip()
        context["symptoms"] = symptoms

        if symptoms:
            try:
                # Construct the prompt for the AI
                prompt = (
                    "A user has the following symptoms: '{symptoms}'. "
                    "Analyze these symptoms and provide a general, non-prescriptive triage suggestion. "
                    "Structure the response in markdown. Start with a friendly greeting. "
                    "Then, provide a section with a summary of possible causes. "
                    "Finally, provide a section with recommendations on what to do next (e.g., rest, see a doctor). "
                    "Begin the entire response with a clear, bolded disclaimer: "
                    "**Disclaimer: This is not a substitute for professional medical advice. Always consult a doctor for any health concerns.**"
                ).format(symptoms=symptoms)

                # Call the AI API
                response = LocalAIApi.create_response(
                    {
                        "input": [
                            {"role": "system", "content": "You are a friendly and helpful healthcare assistant."},
                            {"role": "user", "content": prompt},
                        ],
                    },
                    {
                        "poll_interval": 5,
                        "poll_timeout": 300,
                    },
                )

                if response.get("success"):
                    text = LocalAIApi.extract_text(response)
                    ai_result = text if text else "I am sorry, but I couldn't process your request. Please try again."
                else:
                    logger.error("AI API Error: %s", response.get("error"))
                    ai_result = "There was an error communicating with the AI. Please try again later."

            except Exception as e:
                logger.error("An exception occurred during AI processing: %s", e)
                ai_result = "A system error occurred. Please try again later."

    context["ai_result"] = ai_result
    return render(request, "core/index.html", context)
