#!/usr/bin/env python
"""
telegram_scheduler_v5.py - Advanced school schedule checker with homeroom teacher info using database
"""

import datetime
import csv
import re
import os
from database import SchoolScheduleDB


def find_student_location_and_teacher(student_name_query):
    """
    Find where a student should be based on their name using database
    """
    # Create database instance
    db = SchoolScheduleDB()
    
    # Search for student by name
    students = db.find_student(student_name_query)
    
    if not students:
        print(f"No student found matching '{student_name_query}'")
        db.close()
        return
    
    # Handle multiple student matches
    if len(students) > 1:
        print(f"\nFound {len(students)} students matching '{student_name_query}':")
        for i, (full_name, class_name) in enumerate(students, 1):
            print(f"{i}. {full_name} ({class_name})")
        
        try:
            choice = int(input(f"\nSelect student (1-{len(students)}): ")) - 1
            if 0 <= choice < len(students):
                full_name, class_name = students[choice]
            else:
                print("Invalid selection.")
                db.close()
                return
        except ValueError:
            print("Invalid input.")
            db.close()
            return
    else:
        full_name, class_name = students[0]
    
    # Find the homeroom teacher for this student's class using the database
    homeroom_teacher = db.get_homeroom_teacher(class_name)
    
    # Get current schedule for the student
    current_schedule = get_current_schedule_for_student_db(db, full_name, class_name)
    
    # Display the results
    print(f"\n🔍 STUDENT INFORMATION:")
    print(f"👤 Student: {full_name}")
    print(f"🎒 Class: {class_name}")
    
    if current_schedule:
        print(f"\n📋 TODAY'S SCHEDULE:")
        for period_info in current_schedule:
            subject, teacher, start_time, end_time, room_or_group = period_info
            print(f"  {start_time}-{end_time} | 📚 {subject} | 👨‍🏫 {teacher} | 🚪 {room_or_group}")
    else:
        print(f"\n😊 No scheduled classes for today!")
    
    if homeroom_teacher:
        print(f"\n🏫 HOMEROOM TEACHER INFORMATION:")
        print(f"👨‍🏫 {homeroom_teacher['name']}")
        print(f"📞 Internal Number: {homeroom_teacher['internal_number']}")
        if homeroom_teacher['mobile_number']:
            print(f"📱 Mobile: {homeroom_teacher['mobile_number']}")
        print(f"🏢 Classroom: {homeroom_teacher['classroom']}")
        print(f"🏛️  Parent Meeting Room: {homeroom_teacher['parent_meeting_room']}")
    else:
        print(f"\n❌ Could not find homeroom teacher for class {class_name}")
    
    db.close()


def get_current_schedule_for_student_db(db, student_name, class_name):
    """
    Get the full schedule for a student for the current day from database
    """
    # Get all schedule records for the student
    return db.get_student_schedule(student_name)


def main():
    print("🏫 Advanced School Schedule Checker (Database Version)")
    print("🔍 Find where a student should be and their homeroom teacher info")
    
    # Ask for student name
    name_query = input("\nEnter student name (or part of it): ").strip()
    
    if not name_query:
        print("Please enter a valid name.")
        return
    
    find_student_location_and_teacher(name_query)


if __name__ == "__main__":
    main()