#!/usr/bin/env python3
"""
Test script to verify the new attendance system with proper check-in/check-out logic
"""
import requests
import json
import time
import base64
from PIL import Image
import numpy as np
import cv2

def create_test_image():
    """Create a simple test image"""
    # Create a 100x100 grayscale image
    img_array = np.random.randint(0, 255, (100, 100), dtype=np.uint8)
    img = Image.fromarray(img_array)
    
    # Convert to base64
    import io
    buffer = io.BytesIO()
    img.save(buffer, format='JPEG')
    img_str = base64.b64encode(buffer.getvalue()).decode()
    
    return f"data:image/jpeg;base64,{img_str}"

def test_attendance_system():
    """Test the new attendance system"""
    base_url = "http://localhost:5001"
    
    print("Testing new attendance system...")
    
    # Test 1: Check current attendance data
    print("\n1. Checking current attendance data...")
    try:
        response = requests.get(f"{base_url}/attendance/data")
        if response.status_code == 200:
            data = response.json()
            print(f"Current attendance records: {len(data.get('attendance', []))}")
            for record in data.get('attendance', [])[:3]:  # Show first 3
                print(f"  {record['date']} - {record['user']}: {record['checkin']} to {record['checkout']}")
        else:
            print(f"Error getting attendance data: {response.status_code}")
    except Exception as e:
        print(f"Error: {e}")
    
    # Test 2: Simulate first recognition of the day (should be check-in)
    print("\n2. Testing first recognition (should be check-in)...")
    test_image = create_test_image()
    
    try:
        response = requests.post(f"{base_url}/recognize", 
                               json={'image': test_image})
        if response.status_code == 200:
            result = response.json()
            print(f"Recognition result: {result.get('message', 'No message')}")
            print(f"User: {result.get('user_name', 'Unknown')}")
            print(f"Status: Check-in (first recognition of the day)")
        else:
            print(f"Error: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"Error: {e}")
    
    # Test 3: Simulate subsequent recognition (should update check-out)
    print("\n3. Testing subsequent recognition (should update check-out)...")
    time.sleep(2)  # Wait a bit
    
    try:
        response = requests.post(f"{base_url}/recognize", 
                               json={'image': test_image})
        if response.status_code == 200:
            result = response.json()
            print(f"Recognition result: {result.get('message', 'No message')}")
            print(f"User: {result.get('user_name', 'Unknown')}")
            print(f"Status: Check-out (updating existing record)")
        else:
            print(f"Error: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"Error: {e}")
    
    # Test 4: Check updated attendance data
    print("\n4. Checking updated attendance data...")
    try:
        response = requests.get(f"{base_url}/attendance/data")
        if response.status_code == 200:
            data = response.json()
            print(f"Updated attendance records: {len(data.get('attendance', []))}")
            # Show the latest record
            if data.get('attendance'):
                latest = data['attendance'][-1]
                print(f"Latest record: {latest['date']} - {latest['user']}: {latest['checkin']} to {latest['checkout']}")
        else:
            print(f"Error getting attendance data: {response.status_code}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    test_attendance_system()



