"""
Django Test Views for Storm Logger 2.0
Test views for Django integration testing
"""

import time

from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, render
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.generic import DetailView, ListView

from storm_logger import get_logger

from .models import BusinessMetric, TestModel

logger = get_logger(__name__)


def test_view(request):
    """Basic test view with logging."""
    logger.info("Test view accessed")
    logger.business_metric("page_views", 1)
    
    start_time = time.time()
    
    # Simulate some work
    time.sleep(0.01)
    
    end_time = time.time()
    execution_time = end_time - start_time
    
    logger.performance_metric("view_execution_time", execution_time, threshold=0.1)
    
    return JsonResponse({
        "message": "Test view response",
        "execution_time": execution_time,
        "timestamp": time.time()
    })


def error_view(request):
    """Test view that raises an error."""
    logger.info("Error view accessed")
    logger.business_metric("error_page_views", 1)
    
    try:
        # Simulate an error
        raise ValueError("Test error for Storm Logger testing")
    except ValueError as e:
        logger.error(f"Test error occurred: {e}")
        logger.business_metric("view_errors", 1)
        raise


def slow_view(request):
    """Test view that simulates slow performance."""
    logger.info("Slow view accessed")
    logger.business_metric("slow_page_views", 1)
    
    start_time = time.time()
    
    # Simulate slow operation
    time.sleep(0.05)  # Reduced from 0.5 for faster tests
    
    end_time = time.time()
    execution_time = end_time - start_time
    
    logger.performance_metric("slow_view_time", execution_time, threshold=0.1)
    logger.warning(f"Slow view took {execution_time:.3f}s to execute")
    
    return JsonResponse({
        "message": "Slow view response",
        "execution_time": execution_time,
        "warning": "This view is intentionally slow for testing"
    })


@login_required
def authenticated_view(request):
    """Test view requiring authentication."""
    logger.info(f"Authenticated view accessed by user: {request.user.username}")
    logger.business_metric("authenticated_page_views", 1)
    
    return JsonResponse({
        "message": "Authenticated view response",
        "user": request.user.username,
        "is_authenticated": request.user.is_authenticated
    })


@cache_page(60 * 5)  # Cache for 5 minutes
def cached_view(request):
    """Test view with caching."""
    logger.info("Cached view accessed")
    logger.business_metric("cached_page_views", 1)
    
    return JsonResponse({
        "message": "Cached view response",
        "timestamp": time.time(),
        "cache_duration": 300  # 5 minutes
    })


class TestModelListView(ListView):
    """Test model list view."""
    
    model = TestModel
    template_name = "test_app/test_model_list.html"
    context_object_name = "test_models"
    paginate_by = 10
    
    def get_queryset(self):
        """Get queryset with logging."""
        logger.info("TestModelListView queryset accessed")
        logger.business_metric("model_list_views", 1)
        return TestModel.objects.all().order_by("-created_at")
    
    def get_context_data(self, **kwargs):
        """Get context data with logging."""
        context = super().get_context_data(**kwargs)
        logger.info(f"TestModelListView context prepared with {len(context['test_models'])} items")
        return context


class TestModelDetailView(DetailView):
    """Test model detail view."""
    
    model = TestModel
    template_name = "test_app/test_model_detail.html"
    context_object_name = "test_model"
    
    def get_object(self, queryset=None):
        """Get object with logging."""
        obj = super().get_object(queryset)
        logger.info(f"TestModelDetailView object accessed: {obj.name}")
        logger.business_metric("model_detail_views", 1)
        return obj


def create_test_model(request):
    """Create a test model instance."""
    logger.info("Creating test model")
    
    try:
        model = TestModel.objects.create(
            name=f"Test Model {time.time()}",
            value=42
        )
        logger.info(f"Test model created: {model}")
        logger.business_metric("models_created", 1)
        
        return JsonResponse({
            "message": "Test model created",
            "model_id": model.id,
            "model_name": model.name
        })
    except Exception as e:
        logger.error(f"Error creating test model: {e}")
        logger.business_metric("model_creation_errors", 1)
        return JsonResponse({
            "error": "Failed to create test model",
            "details": str(e)
        }, status=500)


def business_metrics_view(request):
    """View to demonstrate business metrics."""
    logger.info("Business metrics view accessed")
    
    # Track various business metrics
    logger.business_metric("feature_usage", 1, context={"feature": "metrics_view"})
    logger.business_metric("user_engagement", 10, context={"session_id": "test_session"})
    logger.business_metric("revenue_tracking", 99.99, context={"product": "premium_feature"})
    
    # Track performance
    start_time = time.time()
    time.sleep(0.02)  # Simulate work
    end_time = time.time()
    
    logger.performance_metric("metrics_processing_time", end_time - start_time, threshold=0.1)
    
    return JsonResponse({
        "message": "Business metrics tracked",
        "metrics_tracked": 3,
        "processing_time": end_time - start_time
    })


def security_test_view(request):
    """View to test security event logging."""
    logger.info("Security test view accessed")
    
    # Simulate security events
    logger.security_event("test_security_check", "Security test performed", "info")
    
    # Check for suspicious activity
    if request.GET.get("suspicious") == "true":
        logger.security_event("suspicious_activity", "Suspicious parameter detected", "warning")
        return JsonResponse({
            "message": "Suspicious activity detected and logged",
            "action": "security_alert_triggered"
        })
    
    return JsonResponse({
        "message": "Security test completed",
        "status": "secure"
    })