"""
Problem 4: Employee Attendance Tracker
------------------------------------------
Reads attendance data (list of dicts, each with a nested
attendance dict mapping date -> (clock_in, clock_out) tuple)
and reports:
  - Total hours worked per employee, per day
  - Total hours worked per employee overall
  - Employees with perfect attendance (present every date
    that appears anywhere in the dataset)
  - Employees with the most absences
  - Employee with the highest / lowest total attendance (hours)
"""

# ---------------------------------------------------------
# Sample Attendance Data
# ---------------------------------------------------------
attendance_data = [
    {
        "employee_name": "Rajesh Deshpande",
        "attendance": {
            "2024-08-15": ("09:00", "17:00"),
            "2024-08-16": ("09:15", "17:10"),
            "2024-08-17": ("09:05", "18:00"),
        },
    },
    {
        "employee_name": "Sneha Kulkarni",
        "attendance": {
            "2024-08-15": ("09:00", "17:00"),
            "2024-08-17": ("09:00", "17:30"),
        },
    },
    {
        "employee_name": "Amit Joshi",
        "attendance": {
            "2024-08-15": ("09:30", "16:30"),
            "2024-08-16": ("09:00", "17:00"),
            "2024-08-17": ("09:00", "17:00"),
        },
    },
]


def time_to_minutes(time_str):
    """Convert 'HH:MM' string to total minutes since midnight."""
    hours, minutes = time_str.split(":")
    return int(hours) * 60 + int(minutes)


def hours_worked(clock_in, clock_out):
    """Return hours worked (float) given 'HH:MM' clock-in/out strings."""
    minutes_worked = time_to_minutes(clock_out) - time_to_minutes(clock_in)
    return minutes_worked / 60.0


def all_dates_in_dataset(data):
    """Collect the set of every date that appears for any employee."""
    all_dates = set()
    for employee in data:
        for day in employee["attendance"]:
            all_dates.add(day)
    return all_dates


def daily_hours_for_employee(employee):
    """Return a dict of date -> hours worked for one employee."""
    daily_hours = {}
    for day, times in employee["attendance"].items():
        clock_in, clock_out = times
        daily_hours[day] = hours_worked(clock_in, clock_out)
    return daily_hours


def total_hours_for_employee(employee):
    """Sum of hours worked across all recorded days for one employee."""
    total = 0.0
    for day, hours in daily_hours_for_employee(employee).items():
        total += hours
    return total


def perfect_attendance(data):
    """
    Employees who have an attendance record for every date that
    appears anywhere in the dataset (i.e., never absent).
    """
    all_dates = all_dates_in_dataset(data)
    perfect = []

    for employee in data:
        employee_dates = set(employee["attendance"].keys())
        if all_dates.issubset(employee_dates):
            perfect.append(employee["employee_name"])

    return perfect


def absence_counts(data):
    """
    For each employee, count how many of the dataset's overall dates
    they were absent on (i.e., missing from their attendance record).
    """
    all_dates = all_dates_in_dataset(data)
    absences = {}

    for employee in data:
        name = employee["employee_name"]
        employee_dates = set(employee["attendance"].keys())
        missing_dates = all_dates - employee_dates
        absences[name] = len(missing_dates)

    return absences


def rank_by_total_hours(data):
    """Return employees sorted by total hours worked (descending)."""
    employees_copy = data[:]
    ranked = []

    while employees_copy:
        best_index = 0
        best_hours = total_hours_for_employee(employees_copy[0])
        for i in range(1, len(employees_copy)):
            hours = total_hours_for_employee(employees_copy[i])
            if hours > best_hours:
                best_hours = hours
                best_index = i
        ranked.append(employees_copy.pop(best_index))

    return ranked


def print_report(data):
    print("=" * 55)
    print("EMPLOYEE ATTENDANCE REPORT")
    print("=" * 55)

    print("\n--- Daily Hours Worked ---")
    for employee in data:
        print(f"\n{employee['employee_name']}:")
        daily_hours = daily_hours_for_employee(employee)
        for day, hours in daily_hours.items():
            print(f"  {day}: {hours:.2f} hours")
        print(f"  Total: {total_hours_for_employee(employee):.2f} hours")

    print("\n--- Perfect Attendance ---")
    perfect = perfect_attendance(data)
    if len(perfect) == 0:
        print("No employees with perfect attendance across all recorded dates.")
    else:
        for name in perfect:
            print(f"- {name}")

    print("\n--- Absence Counts ---")
    absences = absence_counts(data)
    for name, count in absences.items():
        print(f"{name}: {count} absence(s)")

    print("\n--- Ranked by Total Hours Worked ---")
    ranked = rank_by_total_hours(data)
    for rank, employee in enumerate(ranked, start=1):
        total = total_hours_for_employee(employee)
        print(f"{rank}. {employee['employee_name']} - {total:.2f} hours")

    if len(ranked) > 0:
        print(f"\nMost hours worked: {ranked[0]['employee_name']}")
        print(f"Least hours worked: {ranked[-1]['employee_name']}")

    print("=" * 55)


if __name__ == "__main__":
    print_report(attendance_data)