from django.http import JsonResponse
from django.shortcuts import render
from ai.local_ai_api import LocalAIApi
import logging

logger = logging.getLogger(__name__)

def home(request):
    """
    Render the landing page and handle the content generation form.
    """
    if request.method == 'POST':
        topic = request.POST.get('topic', '').strip()
        form_type = request.POST.get('form_type', 'website')

        if not topic:
            return JsonResponse({'error': 'Please enter a topic.'}, status=400)

        try:
            if form_type == 'website':
                prompt = {
                    "input": [
                        {"role": "system", "content": "You are an expert SEO content strategist. Generate a compelling blog post title and a list of relevant SEO keywords for a given topic. Return the result as a JSON object with two keys: 'title' and 'keywords'. The 'keywords' should be a list of strings."},
                        {"role": "user", "content": f"The topic is: {topic}"},
                    ],
                    "text": {"format": {"type": "json_object"}},
                }
                response = LocalAIApi.create_response(prompt)

                if response.get("success"):
                    payload = LocalAIApi.decode_json_from_response(response)
                    if payload:
                        payload['topic'] = topic
                        return JsonResponse(payload)
                    else:
                        return JsonResponse({'error': 'Failed to generate content. The AI response was not valid JSON.'}, status=500)
                else:
                    logger.warning("AI error: %s", response.get("error"))
                    return JsonResponse({'error': 'Failed to generate content due to an AI error.'}, status=500)

            elif form_type == 'youtube':
                prompt = {
                    "input": [
                        {"role": "system", "content": "You are a YouTube content expert. Generate a catchy title, a list of relevant keywords, and a list of hashtags for a given video topic. Return the result as a JSON object with three keys: 'title', 'keywords', and 'hashtags'. 'keywords' and 'hashtags' should be lists of strings."},
                        {"role": "user", "content": f"The topic is: {topic}"},
                    ],
                    "text": {"format": {"type": "json_object"}},
                }
                response = LocalAIApi.create_response(prompt)

                if response.get("success"):
                    payload = LocalAIApi.decode_json_from_response(response)
                    if payload:
                        payload['topic'] = topic
                        return JsonResponse(payload)
                    else:
                        return JsonResponse({'error': 'Failed to generate content. The AI response was not valid JSON.'}, status=500)
                else:
                    logger.warning("AI error: %s", response.get("error"))
                    return JsonResponse({'error': 'Failed to generate content due to an AI error.'}, status=500)

        except Exception as e:
            logger.error("An unexpected error occurred: %s", e)
            return JsonResponse({'error': 'An unexpected error occurred.'}, status=500)

    return render(request, "core/index.html", {})
