"""
Growth Forecasting Views

Views for displaying growth forecasting, seasonal analysis, capacity planning,
and early warning systems for growth anomalies.
"""

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.utils import timezone
from datetime import datetime, timedelta
import json

from users.models import CustomUser, Branch
from users.growth_forecasting_service import GrowthForecastingService
from users.decorators import role_required


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def growth_forecasting_dashboard(request):
    """
    Main growth forecasting dashboard view
    """
    forecasting_service = GrowthForecastingService()
    
    # Get filter parameters
    branch_id = request.GET.get('branch_id')
    forecast_months = int(request.GET.get('forecast_months', 12))
    
    # Generate comprehensive forecast report
    forecast_report = forecasting_service.generate_comprehensive_forecast_report(branch_id)
    
    # Get branches for filter dropdown
    branches = Branch.objects.filter(is_active=True).order_by('name')
    
    context = {
        'forecast_report': forecast_report,
        'branches': branches,
        'selected_branch': branch_id,
        'forecast_months': forecast_months,
        'page_title': 'Growth Forecasting Dashboard',
        'dashboard_type': 'growth_forecasting'
    }
    
    return render(request, 'users/growth_forecasting_dashboard.html', context)


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def predictive_models_api(request):
    """
    API endpoint for predictive models data
    """
    forecasting_service = GrowthForecastingService()
    
    branch_id = request.GET.get('branch_id')
    forecast_months = int(request.GET.get('forecast_months', 12))
    
    try:
        data = forecasting_service.create_predictive_models(branch_id, forecast_months)
        return JsonResponse(data)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def seasonal_analysis_api(request):
    """
    API endpoint for seasonal trend analysis data
    """
    forecasting_service = GrowthForecastingService()
    
    branch_id = request.GET.get('branch_id')
    years = int(request.GET.get('years', 2))
    
    try:
        data = forecasting_service.implement_seasonal_trend_analysis(branch_id, years)
        return JsonResponse(data)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def capacity_planning_api(request):
    """
    API endpoint for capacity planning data
    """
    forecasting_service = GrowthForecastingService()
    
    branch_id = request.GET.get('branch_id')
    
    try:
        data = forecasting_service.build_capacity_planning_tools(branch_id)
        return JsonResponse(data)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def early_warning_api(request):
    """
    API endpoint for early warning systems data
    """
    forecasting_service = GrowthForecastingService()
    
    branch_id = request.GET.get('branch_id')
    
    try:
        data = forecasting_service.add_early_warning_systems(branch_id)
        return JsonResponse(data)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@login_required
@role_required(['admin', 'team_leader', 'auditor'])
def export_forecast_report(request):
    """
    Export comprehensive forecast report to Excel/PDF
    """
    forecasting_service = GrowthForecastingService()
    
    branch_id = request.GET.get('branch_id')
    format_type = request.GET.get('format', 'excel')  # excel, pdf
    
    try:
        forecast_report = forecasting_service.generate_comprehensive_forecast_report(branch_id)
        
        if format_type == 'excel':
            import pandas as pd
            from io import BytesIO
            
            output = BytesIO()
            
            with pd.ExcelWriter(output, engine='openpyxl') as writer:
                # Executive Summary
                summary_data = []
                for key, value in forecast_report['executive_summary'].items():
                    if isinstance(value, dict):
                        for sub_key, sub_value in value.items():
                            summary_data.append({
                                'Category': key.replace('_', ' ').title(),
                                'Metric': sub_key.replace('_', ' ').title(),
                                'Value': str(sub_value)
                            })
                    else:
                        summary_data.append({
                            'Category': key.replace('_', ' ').title(),
                            'Metric': '',
                            'Value': str(value)
                        })
                
                summary_df = pd.DataFrame(summary_data)
                summary_df.to_excel(writer, sheet_name='Executive Summary', index=False)
                
                # Forecasts
                forecasts_df = pd.DataFrame(forecast_report['detailed_analysis']['predictive_models']['forecasts'])
                forecasts_df.to_excel(writer, sheet_name='Growth Forecasts', index=False)
                
                # Seasonal Analysis
                seasonal_df = pd.DataFrame([
                    {'Month': month, 'Total Clients': data['total_clients'], 'Avg Per Year': data['avg_per_year']}
                    for month, data in forecast_report['detailed_analysis']['seasonal_analysis']['monthly_patterns'].items()
                ])
                seasonal_df.to_excel(writer, sheet_name='Seasonal Analysis', index=False)
                
                # Capacity Planning
                capacity_df = pd.DataFrame(forecast_report['detailed_analysis']['capacity_planning']['hiring_timeline'])
                capacity_df.to_excel(writer, sheet_name='Capacity Planning', index=False)
                
                # Recommendations
                recommendations_df = pd.DataFrame(forecast_report['recommendations'])
                recommendations_df.to_excel(writer, sheet_name='Recommendations', index=False)
            
            output.seek(0)
            
            filename = f'growth_forecast_report_{timezone.now().strftime("%Y%m%d")}'
            response = HttpResponse(
                output.getvalue(),
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            response['Content-Disposition'] = f'attachment; filename="{filename}.xlsx"'
            return response
            
        else:  # PDF format
            from django.template.loader import render_to_string
            from weasyprint import HTML, CSS
            from django.conf import settings
            import os
            
            # Render HTML template
            html_content = render_to_string('users/forecast_report_pdf.html', {
                'forecast_report': forecast_report,
                'generated_date': timezone.now().strftime('%B %d, %Y')
            })
            
            # Generate PDF
            pdf = HTML(string=html_content).write_pdf()
            
            filename = f'growth_forecast_report_{timezone.now().strftime("%Y%m%d")}'
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="{filename}.pdf"'
            return response
            
    except Exception as e:
        return JsonResponse({'error': f'Export failed: {str(e)}'}, status=500)