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

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

# Test configuration
base_url = "https://admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com"
fallback_url = "https://localhost:443"
admin_user = {"username": "rac00n", "password": "1248163264"}

def test_timezone_simple():
    """Simple test to verify timezone is Europe/Berlin"""
    session = requests.Session()
    
    print("Timezone Verification Test (Europe/Berlin)")
    print("=" * 50)
    
    # Test connection
    try:
        test_response = session.get(base_url, verify=True, timeout=5)
        verify_ssl = True
        print(f"✓ Using external URL: {base_url}")
    except:
        base_url_local = fallback_url
        verify_ssl = False
        print(f"ℹ Using fallback URL: {fallback_url}")
    else:
        base_url_local = base_url
    
    # Show current times
    utc_now = datetime.now(ZoneInfo("UTC"))
    berlin_now = datetime.now(ZoneInfo("Europe/Berlin"))
    
    print(f"\nCurrent times:")
    print(f"  UTC:    {utc_now.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"  Berlin: {berlin_now.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # Calculate offset
    time_diff = (berlin_now.hour - utc_now.hour) % 24
    if berlin_now.day != utc_now.day:
        # Handle day boundary
        if berlin_now.day > utc_now.day:
            time_diff = (berlin_now.hour + 24 - utc_now.hour) % 24
        else:
            time_diff = (berlin_now.hour - utc_now.hour - 24) % 24
    
    print(f"  Offset: +{time_diff} hours")
    
    # Login
    response = session.get(f"{base_url_local}/login", verify=verify_ssl)
    if response.status_code != 200:
        print(f"\n✗ 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_local}/login", data=login_data, verify=verify_ssl, allow_redirects=False)
    
    if response.status_code != 302:
        print(f"\n✗ Login failed: {response.status_code}")
        return
    
    print(f"\n✓ Login successful")
    
    # Check dashboard for any timestamps
    print("\nChecking for timestamps in dashboard...")
    response = session.get(f"{base_url_local}/", verify=verify_ssl)
    if response.status_code == 200:
        # Look for time patterns in dashboard
        time_pattern = r'\d{2}:\d{2}:\d{2}'
        times_found = re.findall(time_pattern, response.text)
        if times_found:
            print(f"✓ Found {len(times_found)} timestamps in dashboard")
            # Check if any match current Berlin hour
            berlin_hour = berlin_now.strftime("%H:")
            if any(berlin_hour in time for time in times_found):
                print(f"✓ Timestamps appear to use Berlin time (found {berlin_hour}xx)")
            else:
                print(f"ℹ Could not confirm timezone from timestamps")
        else:
            print("ℹ No timestamps found in dashboard")
    
    # Check audit log
    print("\nChecking audit log for LOGIN timestamp...")
    response = session.get(f"{base_url_local}/audit", verify=verify_ssl)
    if response.status_code == 200:
        # Extract the most recent LOGIN entry
        if "LOGIN_SUCCESS" in response.text:
            # Look for timestamp near LOGIN_SUCCESS
            berlin_time_str = berlin_now.strftime("%Y-%m-%d %H:")
            if berlin_time_str in response.text:
                print(f"✓ Audit log shows Berlin time (contains {berlin_time_str}xx)")
            else:
                utc_time_str = utc_now.strftime("%Y-%m-%d %H:")
                if utc_time_str in response.text:
                    print(f"✗ Audit log might show UTC time (contains {utc_time_str}xx)")
                else:
                    print(f"ℹ Could not determine timezone from audit log")
    
    # Summary
    print("\n" + "=" * 50)
    print("Summary:")
    if time_diff == 1:
        print("✓ System timezone offset: +1 hour (CET - Winter time)")
    elif time_diff == 2:
        print("✓ System timezone offset: +2 hours (CEST - Summer time)")
    else:
        print(f"⚠ Unexpected timezone offset: +{time_diff} hours")
    
    print("\nNote: The system should use Europe/Berlin timezone for all new data.")
    print("Existing data created before the timezone change may still show UTC.")

if __name__ == "__main__":
    test_timezone_simple()