#!/usr/bin/env python3
"""
Migration script to convert attendance log from old format to new check-in/check-out format
"""
import csv
import datetime
import os
import shutil
from collections import defaultdict

def migrate_attendance_log():
    """Convert attendance_log.csv from old format to new format"""
    
    input_file = "attendance_log.csv"
    output_file = "attendance_log_new.csv"
    backup_file = "attendance_log_backup.csv"
    
    print("Starting attendance log migration...")
    
    # Check if input file exists
    if not os.path.exists(input_file):
        print(f"Error: {input_file} not found!")
        return False
    
    # Create backup
    shutil.copy2(input_file, backup_file)
    print(f"Backup created: {backup_file}")
    
    # Read old format and group by date and user
    daily_records = defaultdict(lambda: defaultdict(list))
    
    try:
        with open(input_file, 'r', newline='') as file:
            reader = csv.DictReader(file)
            for row in reader:
                timestamp = row.get('Timestamp', '')
                user_id = row.get('User ID', '')
                user_name = row.get('User Name', '')
                status = row.get('Status', '')
                
                if timestamp and user_id:
                    try:
                        dt = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
                        date_key = dt.strftime("%Y-%m-%d")
                        
                        daily_records[date_key][user_id].append({
                            'timestamp': dt,
                            'user_name': user_name,
                            'status': status
                        })
                    except ValueError:
                        print(f"Warning: Could not parse timestamp: {timestamp}")
                        continue
        
        # Write new format
        with open(output_file, 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(["Date", "User ID", "User Name", "Check-in", "Check-out"])
            
            for date in sorted(daily_records.keys()):
                for user_id in sorted(daily_records[date].keys()):
                    records = daily_records[date][user_id]
                    
                    if records:
                        # Sort records by timestamp
                        records.sort(key=lambda x: x['timestamp'])
                        
                        # First record = check-in, last record = check-out
                        checkin_time = records[0]['timestamp'].strftime("%Y-%m-%d %H:%M:%S")
                        checkout_time = records[-1]['timestamp'].strftime("%Y-%m-%d %H:%M:%S") if len(records) > 1 else ""
                        user_name = records[0]['user_name']
                        
                        writer.writerow([date, user_id, user_name, checkin_time, checkout_time])
                        
                        print(f"Migrated: {date} - User {user_id} ({user_name}): Check-in {checkin_time}, Check-out {checkout_time}")
        
        # Replace old file with new one
        os.replace(output_file, input_file)
        print(f"Migration completed! New format saved to {input_file}")
        
        # Show summary
        total_days = len(daily_records)
        total_users = sum(len(users) for users in daily_records.values())
        print(f"Summary: {total_days} days, {total_users} user-days processed")
        
        return True
        
    except Exception as e:
        print(f"Error during migration: {e}")
        return False

if __name__ == "__main__":
    migrate_attendance_log()
