"""
Generate comprehensive survey analytics report

This command generates detailed analytics for:
- Each survey template (overall metrics)
- Each question within each template (detailed metrics)
- Statistical analysis (correlation, skewness, kurtosis)
- Question rankings and insights
- Trends, correlations, and insights

Usage:
    python manage.py generate_survey_analytics_report
    python manage.py generate_survey_analytics_report --template "Inpatient"
    python manage.py generate_survey_analytics_report --start-date 2025-01-01 --end-date 2025-12-31
    python manage.py generate_survey_analytics_report --json
    python manage.py generate_survey_analytics_report --html
"""
import json
import os
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings

from apps.surveys.models import SurveyTemplate
from apps.surveys.analytics_utils import (
    calculate_survey_analytics,
    generate_markdown_report,
    generate_html_report,
    ReportGenerator,
)


class Command(BaseCommand):
    help = 'Generate comprehensive survey analytics report'

    def add_arguments(self, parser):
        parser.add_argument(
            '--template',
            type=str,
            help='Specific survey template name to analyze',
        )
        parser.add_argument(
            '--start-date',
            type=str,
            help='Start date (YYYY-MM-DD)',
        )
        parser.add_argument(
            '--end-date',
            type=str,
            help='End date (YYYY-MM-DD)',
        )
        parser.add_argument(
            '--json',
            action='store_true',
            help='Generate JSON output file',
        )
        parser.add_argument(
            '--html',
            action='store_true',
            help='Generate HTML output file',
        )
        parser.add_argument(
            '--output-dir',
            type=str,
            default='.',
            help='Output directory for reports',
        )

    def handle(self, *args, **options):
        """Command handler"""
        self.stdout.write(self.style.SUCCESS('Generating Survey Analytics Report...\n'))

        # Parse date range
        start_date, end_date = self._parse_date_range(options)
        self.stdout.write(f'Date Range: {start_date.date()} to {end_date.date()}')

        # Get survey templates
        templates = self._get_survey_templates(options.get('template'))
        self.stdout.write(f'\nAnalyzing {len(templates)} survey template(s)...')

        # Generate analytics data
        analytics_data = calculate_survey_analytics(
            template_name=options.get('template'),
            start_date=start_date.date(),
            end_date=end_date.date()
        )

        # Generate outputs
        self._generate_outputs(analytics_data, options)

        self.stdout.write(self.style.SUCCESS('\n✓ Report generation complete!'))

    def _parse_date_range(self, options):
        """Parse date range from options"""
        start_date = options.get('start_date')
        end_date = options.get('end_date')

        if start_date:
            start_date = datetime.strptime(start_date, '%Y-%m-%d')
            start_date = timezone.make_aware(start_date)
        else:
            start_date = timezone.now() - timedelta(days=365)

        if end_date:
            end_date = datetime.strptime(end_date, '%Y-%m-%d')
            end_date = timezone.make_aware(end_date)
            end_date = end_date.replace(hour=23, minute=59, second=59)
        else:
            end_date = timezone.now()

        return start_date, end_date

    def _get_survey_templates(self, template_name):
        """Get survey templates to analyze"""
        templates = SurveyTemplate.objects.filter(is_active=True)

        if template_name:
            templates = templates.filter(name__icontains=template_name)

        return templates.order_by('name')

    def _generate_outputs(self, analytics_data, options):
        """Generate output files"""
        output_dir = options.get('output_dir', '.')
        os.makedirs(output_dir, exist_ok=True)

        # Generate Markdown report
        report_gen = ReportGenerator()
        report_gen.generate_markdown_to_file(analytics_data, output_dir)
        self.stdout.write(f'✓ Markdown report: {os.path.join(output_dir, "survey_analytics_report.md")}')

        # Generate JSON file if requested
        if options.get('json'):
            self._generate_json_report(analytics_data, output_dir)

        # Generate HTML file if requested
        if options.get('html'):
            report_gen.generate_html_to_file(analytics_data, output_dir)
            self.stdout.write(f'✓ HTML report: {os.path.join(output_dir, "survey_analytics_report.html")}')

    def _generate_json_report(self, data, output_dir):
        """Generate JSON report"""
        output_path = os.path.join(output_dir, 'survey_analytics_data.json')

        with open(output_path, 'w') as f:
            json.dump(data, f, indent=2, default=str)

        self.stdout.write(f'✓ JSON report: {output_path}')