"""
Comprehensive Teaching Session Monitoring System

This module handles:
1. Continuous monitoring of teaching sessions
2. Email alerts at 30, 20, and 10 minutes before sessions
3. Reminders 10 minutes before session end for attendance submission
4. Supervisor notifications when sessions end
5. Continuous creation of recurring sessions
"""

from datetime import datetime, timedelta, time
from src.models import DatabaseContextManager
from src.models.models import (
    TeachingSession, TimetableBlock, Timetable, Tutor,
    Enrollment, Attendance, AttendanceStatus, Reminder,
    NotificationPreference, Supervisor, Student, Course,
    DailyTeachingSession
)
from src.utils import send_email
import uuid
from typing import Dict, List
import threading
import time as time_module
from flask import current_app
import random


class TeachingSessionMonitor:
    """Comprehensive teaching session monitoring system"""
    
    def __init__(self, app=None):
        self.app = app
        self.is_running = False
        self.monitor_thread = None
    
    def _execute_with_retry(self, operation, max_retries=3, base_delay=1):
        """Execute database operation with retry logic for database locks"""
        for attempt in range(max_retries):
            try:
                return operation()
            except Exception as e:
                if "database is locked" in str(e).lower() and attempt < max_retries - 1:
                    # Exponential backoff with jitter
                    delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
                    current_app.logger.warning(f"Database locked, retrying in {delay:.2f}s (attempt {attempt + 1}/{max_retries})")
                    time_module.sleep(delay)
                    continue
                else:
                    raise e
        
    def start_monitoring(self):
        """Start the comprehensive session monitoring system"""
        if self.is_running:
            return
            
        self.is_running = True
        self.monitor_thread = threading.Thread(target=self._monitor_sessions, daemon=True)
        self.monitor_thread.start()
        
        # Log startup message in app context
        if self.app:
            with self.app.app_context():
                current_app.logger.info("🔔 Teaching session monitoring started")
    
    def stop_monitoring(self):
        """Stop the session monitoring system"""
        self.is_running = False
        if self.monitor_thread:
            self.monitor_thread.join(timeout=5)
        
        if self.app:
            with self.app.app_context():
                current_app.logger.info("🔔 Teaching session monitoring stopped")
    
    def _monitor_sessions(self):
        """Main monitoring loop"""
        while self.is_running:
            try:
                # Run all monitoring tasks within app context with retry logic
                if self.app:
                    with self.app.app_context():
                        # Wrap each operation with retry logic
                        self._execute_with_retry(self._create_recurring_sessions)
                        self._execute_with_retry(self._send_session_alerts)
                        self._execute_with_retry(self._send_session_end_reminders)
                        self._execute_with_retry(self._send_supervisor_notifications)
                
                        # Wait 30 minutes before next check (sessions are created daily)
                        time_module.sleep(1800)  # 30 minutes
                
            except Exception as e:
                # Log error within app context if available
                if self.app:
                    try:
                        with self.app.app_context():
                            current_app.logger.error(f"Error in session monitoring: {e}")
                    except:
                        print(f"Error in session monitoring: {e}")
                else:
                    print(f"Error in session monitoring: {e}")
                # Wait longer on error to avoid overwhelming the database
                time_module.sleep(300)  # Wait 5 minutes before retrying
    
    def _create_recurring_sessions(self):
        """Create daily sessions from timetable blocks for today"""
        with DatabaseContextManager() as ctx:
            now = datetime.utcnow()
            today = now.date()
            today_day_of_week = today.weekday()  # 0=Monday, 1=Tuesday, etc.
            
            # Find timetable blocks for today's day of week that should have sessions created
            timetable_blocks = ctx.session.query(TimetableBlock).join(
                Timetable, TimetableBlock.timetable_id == Timetable.id
            ).filter(
                Timetable.approval_status == 'approved',
                Timetable.is_active == True,
                TimetableBlock.is_cancelled == False,
                TimetableBlock.day_of_week == today_day_of_week
            ).all()
            
            current_app.logger.info(f"📅 Found {len(timetable_blocks)} timetable blocks for {today} (day {today_day_of_week})")
            
            sessions_created = 0
            for block in timetable_blocks:
                # Check if we need to create a session for this block today
                if self._should_create_session_for_today(block, today):
                    self._create_daily_session_from_block(block, today, ctx.session)
                    sessions_created += 1
            
            ctx.session.commit()
            
            if sessions_created > 0:
                current_app.logger.info(f"✅ Created {sessions_created} new sessions for {today}")
    
    def _should_create_session_for_today(self, block, today):
        """Check if a session should be created for this timetable block today"""
        with DatabaseContextManager() as ctx:
            # Check if a daily session already exists for this block today
            existing_daily_session = ctx.session.query(DailyTeachingSession).filter(
                DailyTeachingSession.timetable_block_id == block.id,
                DailyTeachingSession.session_date == today
            ).first()
            
            # Also check if a teaching session already exists for this block today
            existing_teaching_session = ctx.session.query(TeachingSession).filter(
                TeachingSession.tutor_id == block.tutor_id,
                TeachingSession.course_id == block.course_id,
                TeachingSession.day_of_week == block.day_of_week,
                TeachingSession.start_time == block.start_time,
                TeachingSession.end_time == block.end_time,
                TeachingSession.recurring == False,  # Only check non-recurring sessions
                TeachingSession.created_at >= today,  # Created today or later
                TeachingSession.created_at < today + timedelta(days=1)  # Before tomorrow
            ).first()
            
            return existing_daily_session is None and existing_teaching_session is None
    
    def _create_daily_session_from_block(self, block, today, session):
        """Create both DailyTeachingSession and TeachingSession from a timetable block"""
        # Get course info for logging
        course = session.query(Course).filter(Course.id == block.course_id).first()
        course_code = course.code if course else "Unknown"
        
        # Create the daily session (for tracking specific dates)
        daily_session = DailyTeachingSession(
            id=str(uuid.uuid4()),
            timetable_block_id=block.id,
            course_id=block.course_id,
            tutor_id=block.tutor_id,
            session_date=today,
            start_time=block.start_time,
            end_time=block.end_time,
            room=block.room or "TBD",
            session_type=block.block_type,
            status='scheduled',
            notes=f"Daily session for {today} from timetable block {block.id}",
            created_by=block.tutor_id,
            is_verified=False,
            attendance_taken=False
        )
        
        session.add(daily_session)
        
        # Create the teaching session (for API compatibility and frontend)
        teaching_session = TeachingSession(
            id=str(uuid.uuid4()),
            timetable_id=block.timetable_id,
            tutor_id=block.tutor_id,
            course_id=block.course_id,
            title=f"{course_code} - {block.block_type.title()}",
            room=block.room or "TBD",
            day_of_week=block.day_of_week,
            start_time=block.start_time,
            end_time=block.end_time,
            session_type=block.block_type,
            recurring=False,  # This is a specific daily session
            status='scheduled',
            notes=f"Auto-generated session for {today} from timetable block {block.id}",
            created_by=block.tutor_id,
            is_verified=False,
            supervisor_tutor_id=block.supervisor_tutor_id
        )
        
        session.add(teaching_session)
        
        # Link the daily session to the teaching session
        daily_session.teaching_session_id = teaching_session.id
        
        current_app.logger.info(f"📅 Created daily session and teaching session for {today}: {block.start_time} - {course_code}")
    
    def _send_session_alerts(self):
        """Send email alerts at 30, 20, and 10 minutes before sessions start"""
        with DatabaseContextManager() as ctx:
            now = datetime.utcnow()
            today = now.date()
            
            # Define alert intervals (in minutes before session start)
            alert_intervals = [30, 20, 10]
            
            for minutes in alert_intervals:
                alert_time = now + timedelta(minutes=minutes)
                time_window_start = alert_time - timedelta(minutes=1)
                time_window_end = alert_time + timedelta(minutes=1)
                
                # Find daily sessions starting in the alert window for today
                upcoming_daily_sessions = ctx.session.query(DailyTeachingSession).filter(
                    DailyTeachingSession.status == 'scheduled',
                    DailyTeachingSession.session_date == today,
                    DailyTeachingSession.start_time >= time_window_start.time(),
                    DailyTeachingSession.start_time <= time_window_end.time()
                ).all()
                
                for daily_session in upcoming_daily_sessions:
                    # Check if alert already sent for this time interval
                    teaching_session_id = getattr(daily_session, 'teaching_session_id', None)
                    if teaching_session_id:
                        existing_reminder = Reminder.safe_query(ctx.session).filter(
                            Reminder.session_id == teaching_session_id,
                            Reminder.reminder_type == f'session_alert_{minutes}min',
                            Reminder.sent_at >= now.date()
                        ).first()
                    else:
                        existing_reminder = None
                    
                    if not existing_reminder:
                        # Send alert to tutor and students
                        self._send_session_alert(daily_session, minutes)
                        
                        # Record reminder
                        teaching_session_id = getattr(daily_session, 'teaching_session_id', None)
                        if teaching_session_id:
                            reminder = Reminder(
                                id=str(uuid.uuid4()),
                                session_id=teaching_session_id,
                                reminder_type=f'session_alert_{minutes}min',
                                message=f"Session starting in {minutes} minutes: {daily_session.course.title if daily_session.course else 'Unknown Course'}",
                                sent_to=daily_session.tutor_id,
                                sent_at=now,
                                status='sent'
                            )
                            ctx.session.add(reminder)
            
            ctx.session.commit()
    
    def _send_session_alert(self, daily_session: DailyTeachingSession, minutes_before: int):
        """Send email alerts to tutor and students about upcoming session"""
        with DatabaseContextManager() as ctx:
            # Send alert to tutor
            self._send_tutor_session_alert(daily_session, minutes_before)
            
            # Send alerts to enrolled students
            self._send_student_session_alerts(daily_session, minutes_before)
    
    def _send_tutor_session_alert(self, daily_session: DailyTeachingSession, minutes_before: int):
        """Send email alert to tutor about upcoming session"""
        with DatabaseContextManager() as ctx:
            tutor = ctx.session.query(Tutor).filter(
                Tutor.id == daily_session.tutor_id
            ).first()
            
            if not tutor:
                return
            
            # Determine urgency level and color
            if minutes_before == 30:
                urgency_level = "Medium Priority"
                urgency_color = "#FFA500"  # Orange
            elif minutes_before == 20:
                urgency_level = "High Priority"
                urgency_color = "#FF6B6B"  # Red
            else:  # 10 minutes
                urgency_level = "URGENT"
                urgency_color = "#DC143C"  # Dark Red
            
            subject = f"🔔 {urgency_level} - Teaching Session in {minutes_before} minutes"
            
            message = f"""
            <html>
                <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                        <div style="background-color: {urgency_color}; color: white; padding: 20px; border-radius: 8px; text-align: center; margin-bottom: 20px;">
                            <h1 style="margin: 0; font-size: 28px;">🔔 Session Alert</h1>
                            <p style="margin: 10px 0 0 0; font-size: 16px;">{urgency_level}</p>
                        </div>
                        
                        <h2 style="color: #2c3e50;">Teaching Session Reminder</h2>
                        <p>Dear {tutor.first_name},</p>
                        <p>This is a reminder that you have a teaching session starting in <strong>{minutes_before} minutes</strong>.</p>
                        
                        <div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid {urgency_color};">
                            <h3 style="margin-top: 0; color: #2c3e50;">Session Details</h3>
                            <p><strong>Course:</strong> {daily_session.course.title if daily_session.course else 'Unknown Course'}</p>
                            <p><strong>Code:</strong> {daily_session.course.code if daily_session.course else 'N/A'}</p>
                            <p><strong>Start Time:</strong> {daily_session.session_date} {daily_session.start_time}</p>
                            <p><strong>End Time:</strong> {daily_session.session_date} {daily_session.end_time}</p>
                            <p><strong>Room:</strong> {daily_session.room}</p>
                            <p><strong>Type:</strong> {daily_session.session_type}</p>
                        </div>
                        
                        <div style="background-color: #e3f2fd; padding: 15px; border-radius: 8px; margin: 20px 0;">
                            <h3 style="margin-top: 0; color: #1976d2;">Preparation Checklist</h3>
                            <ul>
                                <li>✅ Review session materials</li>
                                <li>✅ Prepare attendance sheet</li>
                                <li>✅ Check room availability</li>
                                <li>✅ Arrive 5 minutes early</li>
                            </ul>
                        </div>
                        
                        <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
                        
                        <p style="font-size: 14px; color: #666;">
                            This is an automated reminder from the Kisiwa Timetable Management System.<br>
                            Please ensure you're prepared for your upcoming session.
                        </p>
                        
                        <p style="margin-top: 20px;">
                            Best regards,<br>
                            <strong>Kisiwa Tech Team</strong>
                        </p>
                    </div>
                </body>
            </html>
            """
            
            try:
                sender_email = 'kisiwa@mutabletech.co.ke'
                sender_password = 'z}Y{WN$jV=Sv'
                
                success, result = send_email(sender_email, sender_password, tutor.email, subject, message)
                
                if success:
                    current_app.logger.info(f"✅ Session alert sent to tutor {tutor.first_name} {tutor.last_name} ({minutes_before}min)")
                else:
                    current_app.logger.error(f"❌ Failed to send session alert to tutor: {result}")
                    
            except Exception as e:
                current_app.logger.error(f"❌ Error sending tutor session alert: {e}")
    
    def _send_student_session_alerts(self, daily_session: DailyTeachingSession, minutes_before: int):
        """Send email alerts to enrolled students about upcoming session"""
        with DatabaseContextManager() as ctx:
            # Get enrolled students for this course
            enrollments = ctx.session.query(Enrollment).filter(
                Enrollment.course_id == daily_session.course_id,
                Enrollment.status == 'active'
            ).all()
            
            for enrollment in enrollments:
                student = ctx.session.query(Student).filter(
                    Student.id == enrollment.student_id
                ).first()
                
                if not student:
                    continue
                
                # Check student's notification preferences
                notification_pref = ctx.session.query(NotificationPreference).filter(
                    NotificationPreference.user_id == student.id
                ).first()
                
                if notification_pref and not notification_pref.receive_email:
                    continue
                
                # Determine urgency level and color
                if minutes_before == 30:
                    urgency_level = "Session Reminder"
                    urgency_color = "#4CAF50"  # Green
                elif minutes_before == 20:
                    urgency_level = "Session Starting Soon"
                    urgency_color = "#FF9800"  # Orange
                else:  # 10 minutes
                    urgency_level = "Session Starting Now"
                    urgency_color = "#F44336"  # Red
                
                subject = f"📚 {urgency_level} - {daily_session.course.title if daily_session.course else 'Class'}"
                
                message = f"""
                <html>
                    <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                        <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                            <div style="background-color: {urgency_color}; color: white; padding: 20px; border-radius: 8px; text-align: center; margin-bottom: 20px;">
                                <h1 style="margin: 0; font-size: 28px;">📚 Class Reminder</h1>
                                <p style="margin: 10px 0 0 0; font-size: 16px;">{urgency_level}</p>
                            </div>
                            
                            <h2 style="color: #2c3e50;">Upcoming Class Session</h2>
                            <p>Dear {student.first_name},</p>
                            <p>This is a reminder that you have a class session starting in <strong>{minutes_before} minutes</strong>.</p>
                            
                            <div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid {urgency_color};">
                                <h3 style="margin-top: 0; color: #2c3e50;">Session Details</h3>
                                <p><strong>Course:</strong> {daily_session.course.title if daily_session.course else 'Unknown Course'}</p>
                                <p><strong>Code:</strong> {daily_session.course.code if daily_session.course else 'N/A'}</p>
                                <p><strong>Start Time:</strong> {daily_session.session_date} {daily_session.start_time}</p>
                                <p><strong>End Time:</strong> {daily_session.session_date} {daily_session.end_time}</p>
                                <p><strong>Room:</strong> {daily_session.room}</p>
                                <p><strong>Tutor:</strong> {daily_session.tutor.first_name if daily_session.tutor else 'TBA'} {daily_session.tutor.last_name if daily_session.tutor else ''}</p>
                            </div>
                            
                            <div style="background-color: #e8f5e8; padding: 15px; border-radius: 8px; margin: 20px 0;">
                                <h3 style="margin-top: 0; color: #2e7d32;">Preparation Tips</h3>
                                <ul>
                                    <li>📖 Bring your course materials</li>
                                    <li>📝 Prepare questions for discussion</li>
                                    <li>⏰ Arrive on time</li>
                                    <li>📱 Bring your student ID</li>
                                </ul>
                            </div>
                            
                            <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
                            
                            <p style="font-size: 14px; color: #666;">
                                This is an automated reminder from the Kisiwa Timetable Management System.<br>
                                We look forward to seeing you in class!
                            </p>
                            
                            <p style="margin-top: 20px;">
                                Best regards,<br>
                                <strong>Kisiwa Tech Team</strong>
                            </p>
                        </div>
                    </body>
                </html>
                """
                
                try:
                    sender_email = 'kisiwa@mutabletech.co.ke'
                    sender_password = 'z}Y{WN$jV=Sv'
                    
                    success, result = send_email(sender_email, sender_password, student.email, subject, message)
                    
                    if success:
                        current_app.logger.info(f"✅ Session alert sent to student {student.first_name} {student.last_name} ({minutes_before}min)")
                    else:
                        current_app.logger.error(f"❌ Failed to send session alert to student: {result}")
                        
                except Exception as e:
                    current_app.logger.error(f"❌ Error sending student session alert: {e}")
    
    def _send_session_end_reminders(self):
        """Send reminders 10 minutes before session end for attendance submission"""
        with DatabaseContextManager() as ctx:
            now = datetime.utcnow()
            today = now.date()
            reminder_time = now + timedelta(minutes=10)
            
            # Find daily sessions ending in 10 minutes for today
            sessions_ending = ctx.session.query(DailyTeachingSession).filter(
                DailyTeachingSession.status == 'in_progress',
                DailyTeachingSession.session_date == today,
                DailyTeachingSession.end_time >= (reminder_time - timedelta(minutes=1)).time(),
                DailyTeachingSession.end_time <= (reminder_time + timedelta(minutes=1)).time()
            ).all()
            
            for daily_session in sessions_ending:
                # Check if reminder already sent
                existing_reminder = ctx.session.query(Reminder).filter(
                    Reminder.session_id == daily_session.teaching_session_id,
                    Reminder.reminder_type == 'attendance_submission_reminder',
                    Reminder.sent_at >= now.date()
                ).first()
                
                if not existing_reminder:
                    self._send_attendance_submission_reminder(daily_session)
                    
                    # Record reminder
                    reminder = Reminder(
                        id=str(uuid.uuid4()),
                        session_id=daily_session.teaching_session_id,
                        reminder_type='attendance_submission_reminder',
                        message=f"Session ending soon - Please submit attendance for {daily_session.course.title if daily_session.course else 'Unknown Course'}",
                        sent_to=daily_session.tutor_id,
                        sent_at=now,
                        status='sent'
                    )
                    ctx.session.add(reminder)
            
            ctx.session.commit()
    
    def _send_attendance_submission_reminder(self, daily_session: DailyTeachingSession):
        """Send reminder to tutor to submit attendance"""
        with DatabaseContextManager() as ctx:
            tutor = ctx.session.query(Tutor).filter(
                Tutor.id == daily_session.tutor_id
            ).first()
            
            if not tutor:
                return
            
            subject = "📋 Attendance Submission Reminder - Session Ending Soon"
            
            message = f"""
            <html>
                <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                    <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                        <div style="background-color: #FF9800; color: white; padding: 20px; border-radius: 8px; text-align: center; margin-bottom: 20px;">
                            <h1 style="margin: 0; font-size: 28px;">📋 Attendance Reminder</h1>
                            <p style="margin: 10px 0 0 0; font-size: 16px;">Session Ending Soon</p>
                        </div>
                        
                        <h2 style="color: #2c3e50;">Attendance Submission Required</h2>
                        <p>Dear {tutor.first_name},</p>
                        <p>This is a reminder that your teaching session is ending in <strong>10 minutes</strong>. Please ensure you submit the attendance records to your supervisor.</p>
                        
                        <div style="background-color: #fff3cd; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #ffc107;">
                            <h3 style="margin-top: 0; color: #856404;">Session Details</h3>
                            <p><strong>Course:</strong> {daily_session.course.title if daily_session.course else 'Unknown Course'}</p>
                            <p><strong>Code:</strong> {daily_session.course.code if daily_session.course else 'N/A'}</p>
                            <p><strong>Start Time:</strong> {daily_session.session_date} {daily_session.start_time}</p>
                            <p><strong>End Time:</strong> {daily_session.session_date} {daily_session.end_time}</p>
                            <p><strong>Room:</strong> {daily_session.room}</p>
                        </div>
                        
                        <div style="background-color: #d1ecf1; padding: 15px; border-radius: 8px; margin: 20px 0;">
                            <h3 style="margin-top: 0; color: #0c5460;">Attendance Submission Checklist</h3>
                            <ul>
                                <li>✅ Mark present/absent for each student</li>
                                <li>✅ Note any late arrivals</li>
                                <li>✅ Submit to supervisor within 24 hours</li>
                                <li>✅ Keep attendance records for your records</li>
                            </ul>
                        </div>
                        
                        <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
                        
                        <p style="font-size: 14px; color: #666;">
                            This is an automated reminder from the Kisiwa Timetable Management System.<br>
                            Please ensure attendance is submitted promptly after the session ends.
                        </p>
                        
                        <p style="margin-top: 20px;">
                            Best regards,<br>
                            <strong>Kisiwa Tech Team</strong>
                        </p>
                    </div>
                </body>
            </html>
            """
            
            try:
                sender_email = 'kisiwa@mutabletech.co.ke'
                sender_password = 'z}Y{WN$jV=Sv'
                
                success, result = send_email(sender_email, sender_password, tutor.email, subject, message)
                
                if success:
                    current_app.logger.info(f"✅ Attendance submission reminder sent to tutor {tutor.first_name} {tutor.last_name}")
                else:
                    current_app.logger.error(f"❌ Failed to send attendance submission reminder: {result}")
                    
            except Exception as e:
                current_app.logger.error(f"❌ Error sending attendance submission reminder: {e}")
    
    def _send_supervisor_notifications(self):
        """Send notifications to supervisors when sessions end"""
        with DatabaseContextManager() as ctx:
            now = datetime.utcnow()
            today = now.date()
            
            # Find daily sessions that ended in the last 5 minutes for today
            sessions_ended = ctx.session.query(DailyTeachingSession).filter(
                DailyTeachingSession.status == 'completed',
                DailyTeachingSession.session_date == today,
                DailyTeachingSession.end_time >= (now - timedelta(minutes=5)).time(),
                DailyTeachingSession.end_time <= now.time()
            ).all()
            
            for daily_session in sessions_ended:
                # Check if notification already sent
                existing_notification = ctx.session.query(Reminder).filter(
                    Reminder.session_id == daily_session.teaching_session_id,
                    Reminder.reminder_type == 'supervisor_attendance_review',
                    Reminder.sent_at >= now.date()
                ).first()
                
                if not existing_notification:
                    # Get the supervisor for this course
                    supervisor = ctx.session.query(Supervisor).filter(
                        Supervisor.id == daily_session.course.supervisor_id
                    ).first() if daily_session.course and daily_session.course.supervisor_id else None
                    
                    if supervisor:
                        self._send_supervisor_attendance_review_notification(daily_session, supervisor)
                        
                        # Record notification
                        reminder = Reminder(
                            id=str(uuid.uuid4()),
                            session_id=daily_session.teaching_session_id,
                            reminder_type='supervisor_attendance_review',
                            message=f"Session completed - Please review attendance for {daily_session.course.title if daily_session.course else 'Unknown Course'}",
                            sent_to=supervisor.id,
                            sent_at=now,
                            status='sent'
                        )
                        ctx.session.add(reminder)
            
            ctx.session.commit()
    
    def _send_supervisor_attendance_review_notification(self, daily_session: DailyTeachingSession, supervisor: Supervisor):
        """Send notification to supervisor to review attendance"""
        subject = "📊 Attendance Review Required - Session Completed"
        
        message = f"""
        <html>
            <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
                <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                    <div style="background-color: #2196F3; color: white; padding: 20px; border-radius: 8px; text-align: center; margin-bottom: 20px;">
                        <h1 style="margin: 0; font-size: 28px;">📊 Attendance Review</h1>
                        <p style="margin: 10px 0 0 0; font-size: 16px;">Session Completed</p>
                    </div>
                    
                    <h2 style="color: #2c3e50;">Attendance Review Required</h2>
                    <p>Dear {supervisor.first_name},</p>
                    <p>A teaching session has just completed and requires your attendance review and verification.</p>
                    
                    <div style="background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #2196F3;">
                        <h3 style="margin-top: 0; color: #2c3e50;">Session Details</h3>
                        <p><strong>Course:</strong> {daily_session.course.title if daily_session.course else 'Unknown Course'}</p>
                        <p><strong>Code:</strong> {daily_session.course.code if daily_session.course else 'N/A'}</p>
                        <p><strong>Tutor:</strong> {daily_session.tutor.first_name if daily_session.tutor else 'Unknown'} {daily_session.tutor.last_name if daily_session.tutor else ''}</p>
                        <p><strong>Start Time:</strong> {daily_session.session_date} {daily_session.start_time}</p>
                        <p><strong>End Time:</strong> {daily_session.session_date} {daily_session.end_time}</p>
                        <p><strong>Room:</strong> {daily_session.room}</p>
                        <p><strong>Duration:</strong> {int((datetime.combine(daily_session.session_date, daily_session.end_time) - datetime.combine(daily_session.session_date, daily_session.start_time)).total_seconds() / 60)} minutes</p>
                    </div>
                    
                    <div style="background-color: #e8f5e8; padding: 15px; border-radius: 8px; margin: 20px 0;">
                        <h3 style="margin-top: 0; color: #2e7d32;">Review Checklist</h3>
                        <ul>
                            <li>✅ Verify attendance accuracy</li>
                            <li>✅ Check for any discrepancies</li>
                            <li>✅ Approve or request corrections</li>
                            <li>✅ Provide feedback to tutor if needed</li>
                        </ul>
                    </div>
                    
                    <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
                    
                    <p style="font-size: 14px; color: #666;">
                        This is an automated notification from the Kisiwa Timetable Management System.<br>
                        Please review the attendance records and provide feedback as needed.
                    </p>
                    
                    <p style="margin-top: 20px;">
                        Best regards,<br>
                        <strong>Kisiwa Tech Team</strong>
                    </p>
                </div>
            </body>
        </html>
        """
        
        try:
            sender_email = 'kisiwa@mutabletech.co.ke'
            sender_password = 'z}Y{WN$jV=Sv'
            
            success, result = send_email(sender_email, sender_password, supervisor.email, subject, message)
            
            if success:
                current_app.logger.info(f"✅ Supervisor notification sent to {supervisor.first_name} {supervisor.last_name}")
            else:
                current_app.logger.error(f"❌ Failed to send supervisor notification: {result}")
                
        except Exception as e:
            current_app.logger.error(f"❌ Error sending supervisor notification: {e}")


# Global instance for the session monitor
session_monitor = TeachingSessionMonitor()