#!/usr/bin/env python3
"""
Test script to demonstrate the enhanced attendance logging system
"""
import csv
import datetime
import os

def simulate_attendance_recognition(user_id, user_name, timestamp_str, status):
    """Simulate attendance recognition and show the enhanced logging logic"""
    
    print(f"\n🔍 Simulating recognition for {user_name} (ID: {user_id})")
    print(f"⏰ Time: {timestamp_str}")
    print(f"📝 Status: {status}")
    
    # Parse timestamp
    dt = datetime.datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")
    today = dt.strftime("%Y-%m-%d")
    
    log_file = "attendance_log.csv"
    
    # Read all existing records
    all_records = []
    if os.path.exists(log_file):
        with open(log_file, 'r', newline='') as file:
            reader = csv.DictReader(file)
            all_records = list(reader)
    
    # Check if user has records for today
    today_records = [record for record in all_records 
                    if record['User ID'] == str(user_id) and 
                    record['Timestamp'].startswith(today)]
    
    print(f"\n📊 Current records for {user_name} today:")
    for record in today_records:
        print(f"   {record['Timestamp']} - {record['Status']}")
    
    if not today_records:
        # First time today - this is a check-in
        print(f"✅ First recognition today - Recording CHECK-IN")
        all_records.append({
            'Timestamp': timestamp_str,
            'User ID': str(user_id),
            'User Name': user_name,
            'Status': 'Check-in'
        })
    else:
        # User already has records today - this is a check-out
        print(f"🔄 Subsequent recognition today - Recording CHECK-OUT")
        
        # Check if there's already a check-out record for today
        existing_checkout = None
        for record in today_records:
            if record['Status'] == 'Check-out':
                existing_checkout = record
                break
        
        if existing_checkout:
            # Update existing check-out timestamp
            print(f"🔄 Updating existing check-out timestamp from {existing_checkout['Timestamp']} to {timestamp_str}")
            for record in all_records:
                if (record['User ID'] == str(user_id) and 
                    record['Timestamp'].startswith(today) and 
                    record['Status'] == 'Check-out'):
                    record['Timestamp'] = timestamp_str
                    break
        else:
            # Add new check-out record
            print(f"➕ Adding new check-out record")
            all_records.append({
                'Timestamp': timestamp_str,
                'User ID': str(user_id),
                'User Name': user_name,
                'Status': 'Check-out'
            })
    
    # Write back all records
    with open(log_file, 'w', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=['Timestamp', 'User ID', 'User Name', 'Status'])
        writer.writeheader()
        writer.writerows(all_records)
    
    print(f"💾 Attendance log updated successfully!")

def show_final_attendance():
    """Show the final clean attendance data"""
    print(f"\n📋 FINAL CLEAN ATTENDANCE DATA:")
    print("=" * 60)
    
    log_file = "attendance_log.csv"
    if os.path.exists(log_file):
        with open(log_file, 'r', newline='') as file:
            reader = csv.DictReader(file)
            records = list(reader)
        
        # Group by user and date
        user_daily = {}
        for record in records:
            dt = datetime.datetime.strptime(record['Timestamp'], "%Y-%m-%d %H:%M:%S")
            date_key = dt.strftime("%Y-%m-%d")
            user_key = f"{record['User Name']}_{date_key}"
            
            if user_key not in user_daily:
                user_daily[user_key] = {
                    'user': record['User Name'],
                    'date': date_key,
                    'checkin': None,
                    'checkout': None
                }
            
            if record['Status'] == 'Check-in':
                user_daily[user_key]['checkin'] = dt.strftime("%I:%M %p")
            elif record['Status'] == 'Check-out':
                user_daily[user_key]['checkout'] = dt.strftime("%I:%M %p")
        
        # Display clean data
        for key, data in sorted(user_daily.items()):
            duration = 'N/A'
            if data['checkin'] and data['checkout']:
                duration = 'Complete'
            elif data['checkin']:
                duration = 'Active'
            
            print(f"👤 {data['user']} - {data['date']}")
            print(f"   📥 Check-in:  {data['checkin'] or 'N/A'}")
            print(f"   📤 Check-out: {data['checkout'] or 'N/A'}")
            print(f"   ⏱️  Status:    {duration}")
            print()

def main():
    """Main test function"""
    print("🚀 ENHANCED ATTENDANCE LOGGING SYSTEM TEST")
    print("=" * 60)
    print("This test demonstrates how the system now updates existing")
    print("check-out records instead of creating duplicate entries.")
    print()
    
    # Test scenario: User 332 (Alejo Carreon) gets recognized multiple times
    test_scenarios = [
        ("332", "Alejo Carreon", "2025-08-26 09:15:30", "Check-in"),   # First recognition - Check-in
        ("332", "Alejo Carreon", "2025-08-26 10:30:45", "Check-out"), # Second recognition - Check-out
        ("332", "Alejo Carreon", "2025-08-26 11:45:12", "Check-out"), # Third recognition - Update Check-out
        ("332", "Alejo Carreon", "2025-08-26 14:20:33", "Check-out"), # Fourth recognition - Update Check-out
        ("332", "Alejo Carreon", "2025-08-26 17:30:15", "Check-out"), # Fifth recognition - Update Check-out
    ]
    
    for user_id, user_name, timestamp, status in test_scenarios:
        simulate_attendance_recognition(user_id, user_name, timestamp, status)
    
    show_final_attendance()
    
    print("✅ TEST COMPLETED!")
    print("\n🎯 KEY IMPROVEMENTS:")
    print("   • Only ONE check-in per user per day")
    print("   • Only ONE check-out per user per day (updated with latest time)")
    print("   • Clean, professional attendance data")
    print("   • No duplicate entries cluttering the logs")

if __name__ == "__main__":
    main()

