#!/usr/bin/env python3
import requests
import urllib3
from datetime import datetime
from zoneinfo import ZoneInfo
import json
import time

# Disable SSL warnings for self-signed certificate
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Test configuration
# Use external URL for testing
base_url = "https://admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com"
# Fallback to localhost if external URL is not accessible
fallback_url = "https://localhost:443"
admin_user = {"username": "rac00n", "password": "1248163264"}

def test_timezone_functionality():
    """Test if timestamps are in German timezone (Europe/Berlin)"""
    session = requests.Session()
    
    print("Testing Timezone Functionality (Europe/Berlin)")
    print("=" * 50)
    
    # Test connection to external URL first
    global base_url
    try:
        test_response = session.get(base_url, verify=True, timeout=5)
        print(f"✓ Using external URL: {base_url}")
    except:
        base_url = fallback_url
        print(f"ℹ Using fallback URL: {base_url}")
    
    # Get current time in UTC and Berlin
    utc_now = datetime.now(ZoneInfo("UTC"))
    berlin_now = datetime.now(ZoneInfo("Europe/Berlin"))
    
    print(f"Current UTC time: {utc_now.strftime('%Y-%m-%d %H:%M:%S %Z')}")
    print(f"Current Berlin time: {berlin_now.strftime('%Y-%m-%d %H:%M:%S %Z')}")
    print(f"Time difference: {(berlin_now.hour - utc_now.hour) % 24} hours")
    print()
    
    # Login
    verify_ssl = base_url != fallback_url  # Verify SSL for external URL only
    response = session.get(f"{base_url}/login", verify=verify_ssl)
    if response.status_code != 200:
        print(f"✗ Failed to access login page: {response.status_code}")
        return
    
    login_data = {
        "username": admin_user["username"],
        "password": admin_user["password"]
    }
    
    response = session.post(f"{base_url}/login", data=login_data, verify=verify_ssl, allow_redirects=False)
    
    if response.status_code != 302:
        print(f"✗ Login failed: {response.status_code}")
        return
    
    print("✓ Login successful")
    print()
    
    # Test 1: Create a test license to check created_at timestamp
    print("Test 1: Creating test license to check timestamps...")
    
    # First, get a customer ID or create one
    license_data = {
        "customer_select": "new",
        "customer_name": f"Timezone Test Customer {int(time.time())}",
        "customer_email": f"timezone-test-{int(time.time())}@example.com",
        "license_key": f"AF-{berlin_now.strftime('%Y%m')}T-TEST-TIME-ZONE",
        "license_type": "test",
        "max_sessions": "1",
        "start_date": berlin_now.strftime("%Y-%m-%d"),
        "duration": "1",
        "duration_unit": "days"
    }
    
    response = session.post(f"{base_url}/create", data=license_data, verify=verify_ssl)
    
    if response.status_code == 200:
        print("✓ Test license created")
    else:
        print(f"✗ Failed to create license: {response.status_code}")
    
    # Test 2: Check audit log for timezone
    print("\nTest 2: Checking audit log timestamps...")
    
    response = session.get(f"{base_url}/audit", verify=verify_ssl)
    if response.status_code == 200:
        # Extract the most recent audit log entry timestamp from HTML
        if "CREATE" in response.text and license_data["license_key"] in response.text:
            print("✓ Audit log entry created")
            # Check if timestamps in audit log appear to be in German time
            # This is a simple check - in production you'd parse the HTML properly
            current_hour = berlin_now.strftime("%H:")
            if current_hour in response.text:
                print(f"✓ Audit log shows Berlin time (contains {current_hour})")
            else:
                print(f"⚠ Audit log might show UTC time (doesn't contain {current_hour})")
    else:
        print(f"✗ Failed to access audit log: {response.status_code}")
    
    # Test 3: Check backup functionality for filename timezone
    print("\nTest 3: Testing backup filename timezone...")
    
    response = session.post(f"{base_url}/backup/create", verify=verify_ssl)
    if response.status_code == 302:  # Redirect after backup
        print("✓ Backup created")
        
        # Check backup list
        response = session.get(f"{base_url}/backups", verify=verify_ssl)
        if response.status_code == 200:
            # Check if backup filename contains current Berlin hour
            berlin_hour = berlin_now.strftime("%H")
            if f"_{berlin_hour}" in response.text:
                print(f"✓ Backup filename uses Berlin time (contains hour {berlin_hour})")
            else:
                utc_hour = utc_now.strftime("%H")
                if f"_{utc_hour}" in response.text:
                    print(f"✗ Backup filename might use UTC time (contains hour {utc_hour})")
                else:
                    print("⚠ Could not determine timezone from backup filename")
    else:
        print(f"✗ Failed to create backup: {response.status_code}")
    
    # Test 4: Check session timestamps
    print("\nTest 4: Checking session timestamps...")
    
    response = session.get(f"{base_url}/sessions", verify=verify_ssl)
    if response.status_code == 200:
        print("✓ Accessed sessions page")
        # Active sessions should show current time
        if "Keine aktiven Sessions" not in response.text:
            print("✓ Session data available")
        else:
            print("ℹ No active sessions to check (this is normal)")
    else:
        print(f"✗ Failed to access sessions: {response.status_code}")
    
    # Test 5: Database timezone check
    print("\nTest 5: Summary")
    print("-" * 30)
    
    time_diff = (berlin_now.hour - utc_now.hour) % 24
    if time_diff == 1:
        print("✓ Timezone offset is +1 hour (CET - Central European Time)")
    elif time_diff == 2:
        print("✓ Timezone offset is +2 hours (CEST - Central European Summer Time)")
    else:
        print(f"⚠ Unexpected timezone offset: {time_diff} hours")
    
    print("\nNote: All new timestamps should be in Europe/Berlin timezone")
    print("Existing data might still show UTC until updated")

if __name__ == "__main__":
    test_timezone_functionality()