#!/opt/homebrew/bin/python3.11
"""
Birth UUID Generation Test Script

Purpose: Verify UUID generation logic independently from Rust compilation
Date: 2026-04-27
"""

import hashlib
import subprocess
import json
from datetime import datetime, timezone

def get_mac_address():
    """Get MAC address of primary network interface"""
    result = subprocess.run(['ifconfig'], capture_output=True, text=True)
    lines = result.stdout.split('\n')
    for line in lines:
        if 'ether' in line:
            mac = line.split('ether')[1].strip().split()[0]
            return mac
    return "00:00:00:00:00:00"

def compute_birth_uuid(mac_address, timestamp, username, filename):
    """
    Compute Birth UUID (SHA256 hash)
    
    UUID = SHA256(mac_address|timestamp|username|filename)[0:32]
    """
    key = f"{mac_address}|{timestamp}|{username}|{filename}"
    hash_bytes = hashlib.sha256(key.encode())
    hash_hex = hash_bytes.hexdigest()
    return hash_hex[0:32]

def extract_username_from_path(path):
    """Extract username from sftpgo user home path"""
    relative = path.lstrip('./')
    parts = relative.split('/')
    return parts[0] if parts else 'demo'

def test_uuid_generation():
    """Test UUID generation scenarios"""
    mac = get_mac_address()
    timestamp = datetime.now(timezone.utc).isoformat()
    
    print("=" * 60)
    print("Birth UUID Generation Test")
    print("=" * 60)
    print()
    
    print(f"MAC Address: {mac}")
    print(f"Timestamp: {timestamp}")
    print()
    
    # Test 1: Basic generation
    uuid1 = compute_birth_uuid(mac, timestamp, "demo", "video.mp4")
    print("Test 1 - Basic Generation:")
    print(f"  UUID: {uuid1}")
    print(f"  Length: {len(uuid1)} (expected: 32)")
    assert len(uuid1) == 32, "UUID length should be 32"
    print("  ✓ PASS")
    print()
    
    # Test 2: Different MAC
    uuid2 = compute_birth_uuid("a1:b2:c3:d4:e5:f6", timestamp, "demo", "video.mp4")
    uuid3 = compute_birth_uuid("d4:e5:f6:a1:b2:c3", timestamp, "demo", "video.mp4")
    print("Test 2 - Different MAC:")
    print(f"  UUID (MAC A): {uuid2}")
    print(f"  UUID (MAC B): {uuid3}")
    assert uuid2 != uuid3, "Different MAC should produce different UUID"
    print("  ✓ PASS (UUIDs different)")
    print()
    
    # Test 3: Different Time
    uuid4 = compute_birth_uuid(mac, "2026-01-01T10:00:00Z", "demo", "video.mp4")
    uuid5 = compute_birth_uuid(mac, "2026-01-01T14:00:00Z", "demo", "video.mp4")
    print("Test 3 - Different Time:")
    print(f"  UUID (Time 10:00): {uuid4}")
    print(f"  UUID (Time 14:00): {uuid5}")
    assert uuid4 != uuid5, "Different time should produce different UUID"
    print("  ✓ PASS (UUIDs different)")
    print()
    
    # Test 4: Different User
    uuid6 = compute_birth_uuid(mac, timestamp, "demo", "video.mp4")
    uuid7 = compute_birth_uuid(mac, timestamp, "warren", "video.mp4")
    print("Test 4 - Different User:")
    print(f"  UUID (demo): {uuid6}")
    print(f"  UUID (warren): {uuid7}")
    assert uuid6 != uuid7, "Different user should produce different UUID"
    print("  ✓ PASS (UUIDs different)")
    print()
    
    # Test 5: Same elements = same UUID
    uuid8 = compute_birth_uuid("a1:b2:c3", "2026-01-01T10:00:00Z", "demo", "video.mp4")
    uuid9 = compute_birth_uuid("a1:b2:c3", "2026-01-01T10:00:00Z", "demo", "video.mp4")
    print("Test 5 - Same Elements:")
    print(f"  UUID (call 1): {uuid8}")
    print(f"  UUID (call 2): {uuid9}")
    assert uuid8 == uuid9, "Same elements should produce same UUID"
    print("  ✓ PASS (UUIDs same)")
    print()
    
    # Test 6: Real-world scenario
    print("Test 6 - Real-world Scenario (GOPR0001.mp4):")
    uuid_cam1 = compute_birth_uuid("a1:b2:c3:d4:e5:f6", "2026-01-01T10:00:00Z", "demo", "GOPR0001.mp4")
    uuid_cam2 = compute_birth_uuid("d4:e5:f6:a1:b2:c3", "2026-01-01T10:00:00Z", "demo", "GOPR0001.mp4")
    print(f"  Camera A UUID: {uuid_cam1}")
    print(f"  Camera B UUID: {uuid_cam2}")
    assert uuid_cam1 != uuid_cam2, "Same filename on different cameras should have different UUIDs"
    print("  ✓ PASS (GOPR0001.mp4 handled correctly)")
    print()
    
    print("=" * 60)
    print("All Tests Passed ✓")
    print("=" * 60)
    
    return {
        "mac_address": mac,
        "timestamp": timestamp,
        "sample_uuid": uuid1,
        "test_results": {
            "different_mac": uuid2 != uuid3,
            "different_time": uuid4 != uuid5,
            "different_user": uuid6 != uuid7,
            "same_elements": uuid8 == uuid9,
            "same_filename_different_mac": uuid_cam1 != uuid_cam2
        }
    }

def generate_birth_registration_sample():
    """Generate sample birth_registration JSON"""
    mac = get_mac_address()
    timestamp = datetime.now(timezone.utc).isoformat()
    username = "demo"
    filename = "GOPR0001.mp4"
    
    uuid = compute_birth_uuid(mac, timestamp, username, filename)
    
    birth_registration = {
        "uuid": uuid,
        "registration_source": {
            "mac_address": mac,
            "username": username,
            "timestamp": timestamp,
            "original_path": "./demo",
            "original_filename": filename
        }
    }
    
    print("\nSample birth_registration JSON:")
    print(json.dumps(birth_registration, indent=2))
    
    return birth_registration

if __name__ == "__main__":
    test_uuid_generation()
    generate_birth_registration_sample()