"""Parent engagement dashboard — time spent, task completion, efficiency, login history.

Industry standards:
  - K12 / Edgenuity: show time-on-task + completion rate, NOT live clock
  - FERPA: parent sees ONLY their own child (scoped by parent_user FK)
  - Security: show IP + device + timestamp for fraud detection (IEEE device fingerprinting)
"""
from datetime import timedelta

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.utils import timezone

from exams.models import (
    Student, DailyActiveTime, Submission,
    StudentDayMission, SessionEvent, EngineState,
)

# Industry standard: 12 minutes per lesson/task in K-12 (Khan, Edgenuity avg)
EXPECTED_MIN_PER_TASK = 12


def _format_minutes(m):
    if m < 1:
        return "0 min"
    if m < 60:
        return f"{int(m)} min"
    h = m // 60
    mi = m % 60
    return f"{h}h {mi}m"


def _parse_ua(ua):
    if not ua:
        return "Unknown"
    ua = ua.lower()
    if 'iphone' in ua:
        return "iPhone"
    if 'ipad' in ua:
        return "iPad"
    if 'android' in ua:
        return "Android"
    if 'windows' in ua and 'chrome' in ua:
        return "Chrome / Windows"
    if 'windows' in ua and 'firefox' in ua:
        return "Firefox / Windows"
    if 'windows' in ua:
        return "Windows"
    if 'mac' in ua and 'safari' in ua:
        return "Safari / Mac"
    if 'mac' in ua:
        return "Mac"
    if 'linux' in ua:
        return "Linux"
    return "Other"


def _compute_efficiency(active_min, tasks_done, tasks_assigned):
    """Returns dict with band, ratio, explanation (Roman Urdu)."""
    if active_min < 1 and tasks_done == 0:
        return {
            'band': 'no_activity',
            'ratio': None,
            'label': '⚪ Koi Activity Nahi',
            'color': '#6b7280',
            'message': (
                "Is arsay mein koi activity record nahi hui. "
                "Ghar par parhai ka waqt muqarrar karein aur app istemaal karwayen."
            ),
        }

    if active_min < 10:
        return {
            'band': 'not_enough_data',
            'ratio': None,
            'label': '⚪ Data Abhi Kam Hai',
            'color': '#6b7280',
            'message': (
                "Time tracking abhi shuru hui hai. Kuch din ke baad "
                "taqreeban 1 haftay ka mukammal data nazar aayega."
            ),
        }

    expected_min = max(tasks_assigned, 1) * EXPECTED_MIN_PER_TASK
    time_ratio = active_min / expected_min
    completion_ratio = tasks_done / max(tasks_assigned, 1)

    # Avoid division by zero / very small ratios
    if time_ratio < 0.05:
        time_ratio = 0.05
    efficiency = completion_ratio / time_ratio
    efficiency = round(efficiency, 2)

    if efficiency > 1.4:
        return {
            'band': 'rushing',
            'ratio': efficiency,
            'label': '🟡 Raftaar Zyada — Rushing',
            'color': '#f59e0b',
            'message': (
                f"Bacha tezi se kaam kar raha hai (efficiency {efficiency}x). "
                f"Waqt zyada laga raha hai lekin natija kam — ya guess kar raha hai. "
                f"Poochein: 'Aap ne kya seekha aaj?'"
            ),
        }
    if efficiency >= 0.85:
        return {
            'band': 'on_track',
            'ratio': efficiency,
            'label': '🟢 On Track',
            'color': '#10b981',
            'message': (
                f"Aap ka bacha sahi raftaar se chal raha hai (efficiency {efficiency}x). "
                f"Mehnat aur natija mutanasib hain. Isi tarah jaari rakhein."
            ),
        }
    if efficiency >= 0.5:
        return {
            'band': 'behind',
            'ratio': efficiency,
            'label': '🟡 Thora Peeche',
            'color': '#f59e0b',
            'message': (
                f"Bacha waqt de raha hai lekin kaam thora kam ho raha hai (efficiency {efficiency}x). "
                f"Board exam ke liye rozana 24+ trophies zaroori hain — mehnat barhayein."
            ),
        }
    return {
        'band': 'struggling',
        'ratio': efficiency,
        'label': '🔴 Mushkil Ka Shikar',
        'color': '#ef4444',
        'message': (
            f"Bacha waqt de raha hai lekin kaam bohat kam ho raha hai (efficiency {efficiency}x). "
            f"Wajah poochein — concept samajh mein aa raha hai? Teacher se madad lein."
        ),
    }


@login_required
def portal_parent_engagement(request):
    """Parent's view of child's engagement. FERPA-scoped to own child."""
    user = request.user
    student = Student.objects.filter(parent_user=user, is_active=True).first()
    if student is None:
        return redirect("portal-login")

    now = timezone.now()
    period = (request.GET.get('period') or 'week').lower()
    if period == 'month':
        days = 30
        cutoff = now - timedelta(days=30)
    else:
        days = 7
        cutoff = now - timedelta(days=7)

    # ── Time spent ──
    daily_rows = list(DailyActiveTime.objects.filter(
        student=student, date__gte=cutoff.date()
    ).order_by('date'))

    total_active_sec = sum(r.total_active_seconds for r in daily_rows)
    total_hidden_sec = sum(r.total_hidden_seconds for r in daily_rows)
    total_idle_sec = sum(r.total_idle_seconds for r in daily_rows)
    active_min = total_active_sec // 60

    # ── Tasks ──
    tasks_done = Submission.objects.filter(
        exam__student=student,
        status__in=['graded', 'reviewed'],
        created_at__gte=cutoff,
    ).count()

    engine = EngineState.objects.filter(id=1).first()
    current_day = engine.get_current_day() if (engine and engine.has_started) else 0
    day_start = max(1, current_day - days + 1)
    tasks_assigned = StudentDayMission.objects.filter(
        student=student, day_number__gte=day_start
    ).count() if current_day > 0 else 0

    # ── Efficiency ──
    efficiency = _compute_efficiency(active_min, tasks_done, tasks_assigned)

    # ── Login history ──
    sessions = list(SessionEvent.objects.filter(
        user=student.student_user,
        started_at__gte=cutoff,
    ).order_by('-started_at')[:15])

    login_rows = []
    for s in sessions:
        login_rows.append({
            'ip': s.ip or '—',
            'device': _parse_ua(s.user_agent),
            'when': s.started_at,
            'active': s.active,
        })

    distinct_ips = set(r['ip'] for r in login_rows if r['ip'] != '—')
    distinct_devices = set(r['device'] for r in login_rows if r['device'] != 'Unknown')

    # ── Data start marker (when did time tracking begin?) ──
    tracking_started = None
    first_row = DailyActiveTime.objects.filter(student=student).order_by('date').first()
    if first_row:
        tracking_started = first_row.date

    # ── Daily bar chart (last N days, filled with zeros) ──
    chart_days = []
    day_map = {r.date: r.total_active_seconds // 60 for r in daily_rows}
    for i in range(days - 1, -1, -1):
        d = (now.date() - timedelta(days=i))
        chart_days.append({
            'date': d,
            'label': d.strftime('%d'),
            'minutes': day_map.get(d, 0),
        })

    max_min = max([c['minutes'] for c in chart_days] + [1])

    return render(request, 'exams/portal_parent_engagement.html', {
        'student': student,
        'period': period,
        'days': days,
        'active_minutes': active_min,
        'time_display': _format_minutes(active_min),
        'hidden_minutes': total_hidden_sec // 60,
        'idle_minutes': total_idle_sec // 60,
        'tasks_done': tasks_done,
        'tasks_assigned': tasks_assigned,
        'efficiency': efficiency,
        'login_rows': login_rows,
        'distinct_ip_count': len(distinct_ips),
        'distinct_device_count': len(distinct_devices),
        'tracking_started': tracking_started,
        'chart_days': chart_days,
        'max_min': max_min,
        'suspicious_device_warning': len(distinct_devices) > 2,
    })
