from django.http import HttpResponse
from django.shortcuts import render, redirect
import subprocess
import sys
# Make sure the upload_and_review function is in this file.
import json
import os
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.core.mail import send_mail
from .forms import ContactForm

from django.contrib.auth.models import User
#from django.contrib.auth.forms import UserCreationForm
from django.conf import settings


from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomUserCreationForm

from django.contrib import messages

from django import forms





import logging
logger = logging.getLogger(__name__)

# Configure your API key
#Sgenai.configure(api_key=os.getenv("GOOGLE_API_KEY"))

def index(request):
    return render(request, 'index.html')

def software(request):
    return render(request, 'software.html')

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

def run_script(request):
        script_path = 'scripts/script1.py' # Replace with actual path
        try:
            process = subprocess.run([sys.executable, script_path], capture_output=True, text=True)
            #process = subprocess.run(['/path/to/your/venv/bin/python', script_path], capture_output=True, text=True)
            output = process.stdout if process.returncode == 0 else f"Error: {process.stderr}"
        except Exception as e:
            output = f"Exception: {str(e)}"
        return render(request, 'Result.html', {'output': output})




def signup_view(request):
    try:
        if request.method == 'POST':
            form = CustomUserCreationForm(request.POST)
            if form.is_valid():
                user = form.save()
                # Optionally, send a welcome email
                subject = 'Welcome to SawgrassAI.com!'
                message = 'Thank you for signing up!'
                from_email = settings.DEFAULT_FROM_EMAIL
                recipient_list = [user.email]
                send_mail(subject, message, from_email, recipient_list)
                return redirect('login') # Redirect to login after signup
            #form is invalid
            else:
                return render(request, 'signup.html', {'form':form})
        else: #It is a GET request
            form = CustomUserCreationForm()
    except Exception as e:
        logger.error(f"Error in signup_view: {str(e)}")
        return render(request, 'error.html', {'error': str(e)})

    # Render the signup form (outside the try block)
    return render(request, 'signup.html', {'form': form})




class EmailAuthenticationForm(AuthenticationForm):
    email = forms.EmailField(label="Email", max_length=254, required=True)
    password = forms.CharField(label="Password", widget=forms.PasswordInput, required=True)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Reorder fields
        self.fields = {'email': self.fields['email'], 'password': self.fields['password']}

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            try:
                user = User.objects.get(email=email)
                username = user.username
                self.cleaned_data['username'] = username  # Add username to cleaned_data for auth

                self.user_cache = authenticate(username=username, password=password)
                if self.user_cache is None:
                    raise forms.ValidationError("Invalid email or password.")
                else:
                    self.confirm_login_allowed(self.user_cache)
            except User.DoesNotExist:
                raise forms.ValidationError("Invalid email or password.")

        return self.cleaned_data

def login_view(request):
    if request.method == 'POST':
        form = EmailAuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            return redirect('dashboard')  # Replace with your desired redirect
        else:
            messages.error(request, "Invalid email or password")
    else:
        form = EmailAuthenticationForm()
    return render(request, 'login.html', {'form': form})



def contact_view(request):
    if request.method == 'POST':
            print("POST request received.")
            form = ContactForm(request.POST)
            print("Form data:", request.POST)
            if form.is_valid():
                print("Form is valid.")
                name = form.cleaned_data['name']
                email = form.cleaned_data['email']
                message = form.cleaned_data['message']
                send_mail(
                        subject=f"New Contact Form Submission from {name}",
                        message=message,
                        from_email='support@sawgrassai.com',
                        recipient_list=['support@sawgrassai.com'],
                        fail_silently=False,
                    )
                return render(request, 'success.html')
    return render(request, 'contact.html')