import os
import platform
import json
from django import get_version as django_version
from django.shortcuts import render
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from ai.local_ai_api import LocalAIApi
from .models import ChatMessage, Organization

def home(request):
    """Render the landing screen with AI Chat Assistant."""
    now = timezone.now()
    
    context = {
        "project_name": "AIBiz Platform",
        "django_version": django_version(),
        "python_version": platform.python_version(),
        "current_time": now,
        "project_description": os.getenv("PROJECT_DESCRIPTION", "AI-Driven B2B SaaS Platform for modern enterprises."),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
    }
    return render(request, "core/index.html", context)

@csrf_exempt
def ai_chat(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
            user_message = data.get("message")
            
            if not user_message:
                return JsonResponse({"error": "No message provided"}, status=400)

            # Construct the prompt for the AI
            messages = [
                {"role": "system", "content": "You are AIBiz Assistant, an expert in business workflows, SaaS, and AI automation. Help the user with their business questions concisely and professionally."},
                {"role": "user", "content": user_message},
            ]

            response = LocalAIApi.create_response(
                {"input": messages},
                {"poll_interval": 2, "poll_timeout": 60}
            )

            if response.get("success"):
                ai_reply = LocalAIApi.extract_text(response) or "I'm sorry, I couldn't generate a response."
                
                # Save message to DB if user is authenticated (optional for landing)
                # ChatMessage.objects.create(message=user_message, response=ai_reply)
                
                return JsonResponse({"reply": ai_reply})
            else:
                return JsonResponse({"error": response.get("error", "AI service error")}, status=500)
        except Exception as e:
            return JsonResponse({"error": str(e)}, status=500)
    
    return JsonResponse({"error": "Invalid request"}, status=400)