"""
Safe PDF Report Generation Views with Enhanced Error Handling
"""

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
from django.contrib import messages
from datetime import datetime, timedelta
import io
import logging

logger = logging.getLogger(__name__)

from .reports import (
    generate_dashboard_pdf_report,
    generate_loan_statistics,
    generate_client_statistics,
    generate_payment_statistics,
    generate_comprehensive_reports_statistics,
    generate_enhanced_charts
)


def safe_pdf_generation(dashboard_type, branch_id=None):
    """Safely generate PDF with comprehensive error handling"""
    try:
        pdf_buffer = generate_dashboard_pdf_report(dashboard_type, branch_id=branch_id)
        return pdf_buffer
    except Exception as e:
        logger.error(f"PDF generation failed for {dashboard_type}: {str(e)}")
        # Return a simple error PDF or None
        return None


@login_required
def generate_loans_dashboard_pdf(request):
    """Generate PDF report for loans dashboard"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate PDF with error handling
        pdf_buffer = safe_pdf_generation('loans', branch_id=selected_branch_id)
        
        if pdf_buffer:
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="loans_dashboard_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
            return response
        else:
            # Return a simple text response if PDF generation fails
            response = HttpResponse("PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating loans PDF report: {str(e)}')
        response = HttpResponse(f"Error generating PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def generate_clients_dashboard_pdf(request):
    """Generate PDF report for clients dashboard"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate PDF with error handling
        pdf_buffer = safe_pdf_generation('clients', branch_id=selected_branch_id)
        
        if pdf_buffer:
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="clients_dashboard_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
            return response
        else:
            response = HttpResponse("PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating clients PDF report: {str(e)}')
        response = HttpResponse(f"Error generating PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def generate_payments_dashboard_pdf(request):
    """Generate PDF report for payments dashboard"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate PDF with error handling
        pdf_buffer = safe_pdf_generation('payments', branch_id=selected_branch_id)
        
        if pdf_buffer:
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="payments_dashboard_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
            return response
        else:
            response = HttpResponse("PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating payments PDF report: {str(e)}')
        response = HttpResponse(f"Error generating PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def generate_reports_dashboard_pdf(request):
    """Generate PDF report for reports & analytics dashboard"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate PDF with error handling
        pdf_buffer = safe_pdf_generation('reports', branch_id=selected_branch_id)
        
        if pdf_buffer:
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="reports_dashboard_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
            return response
        else:
            response = HttpResponse("PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating reports PDF report: {str(e)}')
        response = HttpResponse(f"Error generating PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def generate_portfolio_dashboard_pdf(request):
    """Generate PDF report for portfolio dashboard"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate PDF with error handling
        pdf_buffer = safe_pdf_generation('portfolio', branch_id=selected_branch_id)
        
        if pdf_buffer:
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="portfolio_dashboard_report_{datetime.now().strftime("%Y%m%d_%H%M%S")}.pdf"'
            return response
        else:
            response = HttpResponse("PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating portfolio PDF report: {str(e)}')
        response = HttpResponse(f"Error generating PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def generate_custom_analytics_pdf(request):
    """Generate custom analytics PDF based on filters"""
    try:
        # Get filters from request
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        borrower_id = request.GET.get('borrower_id')
        loan_product_id = request.GET.get('loan_product_id')
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Parse dates
        if start_date:
            start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        if end_date:
            end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        
        # Get borrower and loan product objects if specified
        borrower = None
        loan_product = None
        
        if borrower_id:
            from users.models import CustomUser
            try:
                borrower = CustomUser.objects.get(id=borrower_id)
            except CustomUser.DoesNotExist:
                pass
        
        if loan_product_id:
            from .models import LoanProduct
            try:
                loan_product = LoanProduct.objects.get(id=loan_product_id)
            except LoanProduct.DoesNotExist:
                pass
        
        # Generate statistics with filters
        stats = generate_loan_statistics(
            start_date=start_date,
            end_date=end_date,
            borrower=borrower,
            loan_product=loan_product,
            branch_id=selected_branch_id
        )
        
        # Generate charts
        charts = generate_enhanced_charts(stats)
        
        # Generate PDF
        from .reports import generate_enhanced_pdf_report
        report_type = 'borrower' if borrower else 'general'
        pdf_buffer = generate_enhanced_pdf_report(stats, charts, report_type, borrower)
        
        if pdf_buffer:
            filename = f"custom_analytics_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
            response = HttpResponse(pdf_buffer.getvalue(), content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename="{filename}"'
            return response
        else:
            response = HttpResponse("Custom PDF generation temporarily unavailable. Please try again later.", content_type='text/plain')
            return response
            
    except Exception as e:
        logger.error(f'Error generating custom analytics PDF: {str(e)}')
        response = HttpResponse(f"Error generating custom PDF: {str(e)}", content_type='text/plain')
        return response


@login_required
def analytics_dashboard(request):
    """Analytics dashboard with PDF generation options"""
    try:
        selected_branch_id = request.session.get('selected_branch_id')
        
        # Generate quick statistics for display with error handling
        try:
            loan_stats = generate_loan_statistics(branch_id=selected_branch_id)
        except Exception as e:
            logger.error(f"Error generating loan statistics: {e}")
            loan_stats = {'basic_metrics': {}, 'performance_metrics': {}}
        
        try:
            client_stats = generate_client_statistics(branch_id=selected_branch_id)
        except Exception as e:
            logger.error(f"Error generating client statistics: {e}")
            client_stats = {'basic_metrics': {}}
        
        try:
            payment_stats = generate_payment_statistics(branch_id=selected_branch_id)
        except Exception as e:
            logger.error(f"Error generating payment statistics: {e}")
            payment_stats = {'basic_metrics': {}}
        
        # Get available filters
        from .models import LoanProduct
        from users.models import CustomUser
        
        loan_products = LoanProduct.objects.filter(is_active=True)
        borrowers = CustomUser.objects.filter(role='borrower')
        
        if selected_branch_id:
            borrowers = borrowers.filter(branch_id=selected_branch_id)
        
        context = {
            'loan_stats': loan_stats,
            'client_stats': client_stats,
            'payment_stats': payment_stats,
            'loan_products': loan_products,
            'borrowers': borrowers[:100],  # Limit for performance
            'today': timezone.now().date(),
        }
        
        return render(request, 'loans/analytics_dashboard.html', context)
        
    except Exception as e:
        logger.error(f'Error loading analytics dashboard: {str(e)}')
        messages.error(request, f'Error loading analytics dashboard: {str(e)}')
        # Return basic template with empty context
        return render(request, 'loans/analytics_dashboard.html', {
            'loan_stats': {'basic_metrics': {}, 'performance_metrics': {}},
            'client_stats': {'basic_metrics': {}},
            'payment_stats': {'basic_metrics': {}},
            'loan_products': [],
            'borrowers': [],
            'today': timezone.now().date(),
        })
