#!/usr/bin/env python3
import requests
import urllib3
from datetime import datetime
from zoneinfo import ZoneInfo
import time
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_audit_timezone():
    """Test audit log timezone specifically"""
    session = requests.Session()
    
    print("Audit Log Timezone Test")
    print("=" * 50)
    
    # Test connection
    try:
        test_response = session.get(base_url, verify=True, timeout=5)
        verify_ssl = True
        base_url_local = base_url
        print(f"✓ Using external URL: {base_url}")
    except:
        base_url_local = fallback_url
        verify_ssl = False
        print(f"ℹ Using fallback URL: {fallback_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')}")
    print(f"  Offset: +{(berlin_now.hour - utc_now.hour) % 24} hours")
    
    # First logout if already logged in
    session.get(f"{base_url_local}/logout", verify=verify_ssl)
    time.sleep(1)
    
    # Login (this will create a new audit log entry)
    print(f"\nPerforming login at {berlin_now.strftime('%H:%M:%S')} Berlin time...")
    
    response = session.get(f"{base_url_local}/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_local}/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")
    
    # Immediately check audit log
    print("\nChecking audit log for fresh LOGIN_SUCCESS entry...")
    response = session.get(f"{base_url_local}/audit", verify=verify_ssl)
    
    if response.status_code == 200:
        # Look for timestamps in the audit log
        # Pattern to find timestamps in format YYYY-MM-DD HH:MM:SS
        timestamp_pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'
        
        # Find all timestamps
        timestamps = re.findall(timestamp_pattern, response.text)
        
        if timestamps:
            print(f"✓ Found {len(timestamps)} timestamps in audit log")
            
            # Check the most recent timestamp (should be first in list)
            if timestamps:
                latest_timestamp = timestamps[0]
                print(f"\nMost recent timestamp: {latest_timestamp}")
                
                # Extract hour from timestamp
                hour_match = re.search(r' (\d{2}):', latest_timestamp)
                if hour_match:
                    log_hour = int(hour_match.group(1))
                    berlin_hour = berlin_now.hour
                    utc_hour = utc_now.hour
                    
                    print(f"  Timestamp hour: {log_hour:02d}")
                    print(f"  Berlin hour:    {berlin_hour:02d}")
                    print(f"  UTC hour:       {utc_hour:02d}")
                    
                    if log_hour == berlin_hour:
                        print("\n✓ Audit log is using Berlin time!")
                    elif log_hour == utc_hour:
                        print("\n✗ Audit log appears to be using UTC time")
                        print("  → Docker containers may need to be rebuilt")
                    else:
                        print("\n⚠ Could not determine timezone (timestamp doesn't match either timezone)")
        else:
            print("✗ No timestamps found in audit log")
        
        # Also check for "vor X Minuten" text which might indicate timezone
        if "vor 0 Minuten" in response.text or "vor 1 Minute" in response.text:
            print("\n✓ Recent entries found (German time format)")
    else:
        print(f"✗ Failed to access audit log: {response.status_code}")
    
    print("\n" + "=" * 50)
    print("If timestamps show UTC instead of Berlin time:")
    print("1. Run: docker-compose down")
    print("2. Run: docker-compose build --no-cache")
    print("3. Run: docker-compose up -d")

if __name__ == "__main__":
    test_audit_timezone()