from django.shortcuts import render, redirect, get_object_or_404

def landing_page(request):
    return render(request, 'core/landing_page.html')
from django.contrib.auth.decorators import login_required
from .models import Post
from .forms import PostForm, SignUpForm
import logging
import os
import json
from django.contrib.auth import login
from ai.local_ai_api import LocalAIApi

logger = logging.getLogger(__name__)

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            return redirect('social_feed')
    else:
        form = SignUpForm()
    return render(request, 'core/signup.html', {'form': form})


def social_feed(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user

            # AI Intent Analysis
            try:
                content = form.cleaned_data['content']
                prompt = (
                    "Analyze the following post and classify its intent into one of "
                    "the following categories: Neutral, Safe, Caution, Warning. "
                    "Only return the category name and nothing else."
                )

                response = LocalAIApi.create_response(
                    {
                        "input": [
                            {"role": "system", "content": prompt},
                            {"role": "user", "content": content}
                        ],
                    },
                )

                if response.get("success"):
                    ai_intent = LocalAIApi.extract_text(response)
                    if ai_intent in ["Neutral", "Safe", "Caution", "Warning"]:
                        post.intent = ai_intent
                    else:
                        post.intent = "Neutral"
                else:
                    post.intent = "Neutral"

            except Exception as e:
                logger.error("Error during AI intent analysis: %s", e)
                post.intent = "Neutral"

            post.save()
            return redirect('social_feed')
    else:
        form = PostForm()

    posts = Post.objects.all().order_by('-created_at')
    context = {
        'posts': posts,
        'form': form,
    }
    return render(request, 'core/index.html', context)


def image_generator(request):
    if request.method == 'POST':
        prompt = request.POST.get('prompt')

        try:
            response = LocalAIApi.create_response({
                "input": [
                    {
                        "role": "system",
                        "content": "You are an AI image generator. Create an image based on the user's prompt."
                    },
                    {"role": "user", "content": prompt}
                ],
                "model": "dall-e-3",
                "parameters": {
                    "size": "1024x1024"
                }
            })

            if response.get("success"):
                data = response.get("data", {})
                output = data.get("output", [])
                image_url = None
                for item in output:
                    if item.get("type") == "image":
                        image_url = item.get("url")
                        break
                if image_url:
                    return render(request, 'core/image_generator.html', {'image_url': image_url})
                else:
                    error_message = "Image URL not found in the response."
                    return render(request, 'core/image_generator.html', {'error_message': error_message})
            else:
                error_message = response.get("error", "An unknown error occurred.")
                return render(request, 'core/image_generator.html', {'error_message': error_message})

        except Exception as e:
            logger.error("Error during image generation: %s", e)
            error_message = str(e)
            return render(request, 'core/image_generator.html', {'error_message': error_message})

    return render(request, 'core/image_generator.html')


def ad_generator(request):
    if request.method == 'POST':
        product_name = request.POST.get('product_name')
        product_description = request.POST.get('product_description')
        target_audience = request.POST.get('target_audience')

        try:
            # Generate ad copy
            ad_copy_prompt = f"Create a compelling ad copy for a product named '{product_name}'. " \
                           f"The product is about: {product_description}. " \
                           f"The target audience is {target_audience}."
            
            ad_copy_response = LocalAIApi.create_response({
                "input": [
                    {"role": "system", "content": "You are an expert copywriter."},
                    {"role": "user", "content": ad_copy_prompt}
                ]
            })
            if ad_copy_response.get("success"):
                ad_copy = LocalAIApi.extract_text(ad_copy_response)
            else:
                ad_copy = "Could not generate ad copy."

            # Generate ad image
            ad_image_prompt = f"Create a visually appealing image for an ad for '{product_name}'. " \
                            f"{product_description}"

            ad_image_response = LocalAIApi.create_response({
                "input": [
                    {
                        "role": "system",
                        "content": "You are an AI image generator. Create an image for an ad based on the user's prompt."
                    },
                    {"role": "user", "content": ad_image_prompt}
                ],
                "model": "dall-e-3",
                "parameters": {
                    "size": "1024x1024"
                }
            })

            if ad_image_response.get("success"):
                data = ad_image_response.get("data", {})
                output = data.get("output", [])
                ad_image_url = None
                for item in output:
                    if item.get("type") == "image":
                        ad_image_url = item.get("url")
                        break
            else:
                ad_image_url = ""


            return render(request, 'core/ad_generator.html', {
                'ad_copy': ad_copy,
                'ad_image_url': ad_image_url,
                'product_name': product_name,
                'product_description': product_description,
                'target_audience': target_audience,
            })

        except Exception as e:
            logger.error("Error during ad generation: %s", e)
            error_message = str(e)
            return render(request, 'core/ad_generator.html', {'error_message': error_message})

    return render(request, 'core/ad_generator.html')

def graphics_editor(request):
    return render(request, 'core/graphics_editor.html')


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def ai_chat(request):
    if request.method == 'POST':
        prompt = request.POST.get('prompt')
        
        # Basic validation
        if not prompt:
            return JsonResponse({'error': 'Prompt is required.'}, status=400)

        try:
            conversation = [
                {
                    "role": "system",
                    "content": (
                        "You are a helpful assistant that can control a web browser. "
                        "You can perform tasks like navigating to web pages, filling out forms, and clicking on links. "
                        "When asked to perform a browser action, you should respond with a JavaScript code block to be executed in the browser. "
                        "The browser is displayed in an iframe, and you can access it using `window.frames[0]`. "
                        "For example, to navigate to a new page, you can use `window.frames[0].location.href = 'https://www.google.com';`. "
                        "To click a button, you can use `window.frames[0].document.querySelector('#my-button').click();`. "
                        "To fill out an input field, you can use `window.frames[0].document.querySelector('#my-input').value = 'my value';`. "
                        "To get the text content of an element, you can use `window.frames[0].document.querySelector('#my-element').textContent`. "
                        "If you are not being asked to do a browser action, you can respond with a conversational response."
                    )
                },
                {"role": "user", "content": prompt}
            ]
            
            response = LocalAIApi.create_response(
                {
                    "input": conversation,
                }
            )

            if response.get("success"):
                return JsonResponse(response)
            else:
                error_message = response.get("error", "An unknown error occurred.")
                return JsonResponse({'error': error_message}, status=500)

        except Exception as e:
            logger.error("Error in ai_chat view: %s", e)
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Only POST requests are allowed.'}, status=405)

def post_list(request):
    posts = Post.objects.all().order_by('-created_at')
    return render(request, 'core/blog.html', {'posts': posts})

def post_detail(request, slug):
    post = get_object_or_404(Post, slug=slug)
    return render(request, 'core/article_detail.html', {'post': post})