import requests
from django.conf import settings
from django.http import HttpResponse
from django.core.exceptions import ImproperlyConfigured

class JasperReport:
    def __init__(self):
        # We check for settings and raise a clear error if they are missing
        try:
            self.base_url = getattr(settings, 'JASPER_SERVER_URL')
            self.user = getattr(settings, 'JASPER_USER')
            self.password = getattr(settings, 'JASPER_PASSWORD')
        except AttributeError:
            raise ImproperlyConfigured(
                "JasperReport Missing Configuration: "
                "Ensure JASPER_SERVER_URL, JASPER_USER, and JASPER_PASSWORD are set in settings.py"
            )

        self.auth = (self.user, self.password)

    def generate(self, report_path, fmt='pdf', params=None):
        url = f"{self.base_url.rstrip('/')}/rest_v2/reports{report_path}.{fmt}"
        
        # Comprehensive list of Jasper-supported content types
        content_types = {
            'pdf': 'application/pdf',
            'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xls': 'application/vnd.ms-excel',
            'csv': 'text/csv',
            'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'rtf': 'application/rtf',
            'html': 'text/html',
            'xml': 'application/xml',
            'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'odt': 'application/vnd.oasis.opendocument.text',
            'ods': 'application/vnd.oasis.opendocument.spreadsheet'
        }
        
        try:
            response = requests.get(url, auth=self.auth, params=params, stream=True)
            response.raise_for_status()
            
            django_res = HttpResponse(
                response.content, 
                content_type=content_types.get(fmt.lower(), 'application/octet-stream')
            )
            django_res['Content-Disposition'] = f'attachment; filename="report.{fmt}"'
            return django_res
            
        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"Jasper Server Communication Error: {str(e)}")