import os
import platform
import json

from django import get_version as django_version
from django.contrib.auth import login
from django.shortcuts import redirect, render, get_object_or_404
from django.utils import timezone
from django.contrib.auth.decorators import login_required

from .models import Article, Reflection
from .forms import SignUpForm, ArticleForm, ReflectionForm
from ai.local_ai_api import LocalAIApi

def home(request):
    """Render the landing screen with loader and environment details.""" 
    host_name = request.get_host().lower()
    agent_brand = "AppWizzy" if host_name == "appwizzy.com" else "Flatlogic"
    now = timezone.now()

    context = {
        "project_name": "New Style",
        "agent_brand": agent_brand,
        "django_version": django_version(),
        "python_version": platform.python_version(),
        "current_time": now,
        "host_name": host_name,
        "project_description": os.getenv("PROJECT_DESCRIPTION", ""),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
    }
    return render(request, "core/index.html", context)

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

@login_required
def article_list(request):
    articles = Article.objects.filter(author=request.user)
    return render(request, 'core/article_list.html', {'articles': articles})

@login_required
def article_detail(request, pk):
    article = get_object_or_404(Article, pk=pk, author=request.user)
    return render(request, 'core/article_detail.html', {'article': article})

@login_required
def article_create(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.save()
            return redirect('article_detail', pk=article.pk)
    else:
        form = ArticleForm()
    return render(request, 'core/article_form.html', {'form': form})


@login_required
def reflection_view(request):
    # AI-generated question
    response = LocalAIApi.create_response({
        "input": [
            {"role": "system", "content": "You are a helpful assistant. Your task is to ask a single, short, thought-provoking question to help a user reflect on their week. The question should be suitable for a professional in the tech industry. The question should be no more than 20 words."},
            {"role": "user", "content": "Ask me a question."},
        ],
    })

    if response.get("success"):
        question = LocalAIApi.extract_text(response)
    else:
        question = "What is your biggest challenge this week?" # Fallback question

    if request.method == 'POST':
        form = ReflectionForm(request.POST)
        if form.is_valid():
            reflection = form.save(commit=False)
            reflection.user = request.user
            reflection.question = request.POST.get('question') # Get question from hidden input
            
            # AI-generated feedback
            feedback_response = LocalAIApi.create_response({
                "input": [
                    {"role": "system", "content": "You are a helpful assistant. Your task is to provide brief, encouraging, and constructive feedback on a user\'s reflection. The feedback should be no more than 50 words."},
                    {"role": "user", "content": f"The user was asked: '{reflection.question}' and they responded: '{reflection.answer}'. Please provide some feedback."},
                ],
            })

            if feedback_response.get("success"):
                reflection.feedback = LocalAIApi.extract_text(feedback_response)
            else:
                reflection.feedback = "Thank you for your reflection." # Fallback feedback

            reflection.save()
            return redirect('reflection')
    else:
        form = ReflectionForm()

    reflections = Reflection.objects.filter(user=request.user).order_by('-created_at')
    return render(request, 'core/reflection.html', {'form': form, 'question': question, 'reflections': reflections})
