from django.core.management.base import BaseCommand
from django.urls import get_resolver, reverse, NoReverseMatch
from django.test import Client
from exams.guide_registry import get_guide
from django.contrib.auth import get_user_model
import re

class Command(BaseCommand):
    help = 'Enterprise UI/UX Audit (Phase 7)'

    def handle(self, *args, **kwargs):
        self.stdout.write(self.style.MIGRATE_HEADING("\n=== IDEALOGY UX AUDIT ENGINE (WCAG 2.2) ===\n"))

        c = Client()
        User = get_user_model()
        admin = User.objects.filter(is_superuser=True).first()
        if admin:
            c.force_login(admin)

        routes = self.get_all_routes(get_resolver().url_patterns)
        results = []

        ignore_list = [
            'api-root', 'whoami', 'submission-list', 'task-list', 
            'attendance-list', 'exam-list', 'parent-report-list', 
            'student-list', 'whatsapp-log-list', 'portal-gem-chain', 
            'portal-gem-home', 'portal-glossary-search', 'portal-heartbeat', 
            'portal-logout', 'portal-model-paper-submit', 'portal-teacher-live-data', 
            'portal-teacher-ops-sitrep', 'portal-teacher-orphans-save', 'portal-translate', 'engine_status', 'engine_toggle',
            'portal-tier-copy',
        ]

        for route_name in routes:
            if route_name.startswith('admin') or route_name.startswith('api_') or not route_name or '<' in route_name:
                continue
            if route_name in ignore_list:
                continue

            try:
                url = reverse(route_name)
                r = c.get(url, follow=True)
                html = r.content.decode('utf-8', errors='ignore')
            except Exception:
                continue

            if r.status_code == 404: 
                continue

            # 1. Guide Check
            has_help_icon = 'floating-help-btn' in html or 'help-btn' in html
            guide = get_guide(route_name)
            guide_status = 'PASS' if (has_help_icon and guide) else ('ICON_ONLY' if has_help_icon else 'MISSING')

            # 2. Inline CSS Check
            has_inline_styles = 'style="' in html.replace('style="width:', '').replace('style="--', '')

            # 3. Accessibility: Missing Labels (WCAG 3.3.2)
            inputs = re.findall(r'<input[^>]*>', html)
            unlabeled_inputs = 0
            for inp in inputs:
                if 'type="hidden"' in inp or 'type="submit"' in inp:
                    continue
                if 'aria-label' not in inp and 'id=' not in inp:
                    unlabeled_inputs += 1

            # 4. Accessibility: Modal Roles (WCAG 4.1.2)
            has_modal_role = 'role="dialog"' in html and 'aria-modal="true"' in html

            # 5. Responsive: Unwrapped Tables (WCAG 1.4.10)
            tables = html.count('<table')
            table_wraps = html.count('class="table-wrap') + html.count('class="table-responsive')
            unwrapped_tables = max(0, tables - table_wraps)

            # 6. Navigation Check
            has_nav = 'global-history-nav' in html

            # Calculate Overall Status
            overall = 'PASS'
            if guide_status != 'PASS' or has_inline_styles or unlabeled_inputs > 0 or not has_modal_role or unwrapped_tables > 0:
                overall = 'FAIL'

            results.append({
                'route': route_name,
                'guide': guide_status,
                'overall': overall,
                'inline': has_inline_styles,
                'unlabeled': unlabeled_inputs,
                'modal': has_modal_role,
                'tables': unwrapped_tables
            })

        self.generate_report(results)

    def get_all_routes(self, url_patterns):
        routes = []
        for pattern in url_patterns:
            if hasattr(pattern, 'url_patterns'):
                routes.extend(self.get_all_routes(pattern.url_patterns))
            elif pattern.name:
                routes.append(pattern.name)
        return list(set(routes))

    def generate_report(self, results):
        self.stdout.write(f"{'ROUTE':<30} | {'GUIDE':<8} | {'A11Y':<6} | {'MODAL':<5} | {'TABLES':<6} | {'OVERALL'}")
        self.stdout.write("-" * 75)
        passes = 0

        for res in sorted(results, key=lambda x: x['route']):
            a11y = 'PASS' if res['unlabeled'] == 0 else f"FAIL({res['unlabeled']})"
            modal = 'PASS' if res['modal'] else 'FAIL'
            tables = 'PASS' if res['tables'] == 0 else f"FAIL({res['tables']})"

            color = self.style.SUCCESS if res['overall'] == 'PASS' else self.style.ERROR
            if res['overall'] == 'PASS': passes += 1

            self.stdout.write(f"{res['route'][:30]:<30} | {res['guide']:<8} | {a11y:<6} | {modal:<5} | {tables:<6} | {color(res['overall'])}")

        self.stdout.write("-" * 75)
        self.stdout.write(f"\nTotal: {len(results)} | PASS: {passes} | FAIL: {len(results)-passes}\n")
