#!/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_simple():
    """Simple test to check audit log timestamps"""
    session = requests.Session()
    
    print("Audit Log Timezone Check")
    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"  Difference: {(berlin_now.hour - utc_now.hour) % 24} hours")
    
    # Login
    response = session.get(f"{base_url_local}/login", verify=verify_ssl)
    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")
        return
    
    print("✓ Login successful")
    
    # Create a distinctive action to find in audit log
    print("\nCreating a test action...")
    
    # Try to access customers page (this will create an audit entry)
    response = session.get(f"{base_url_local}/customers", verify=verify_ssl)
    
    # Now check audit log
    print("\nChecking audit log...")
    response = session.get(f"{base_url_local}/audit", verify=verify_ssl)
    
    if response.status_code == 200:
        # Look for table rows with class="table"
        # Extract just the table content
        table_match = re.search(r'<table class="table[^>]*>(.*?)</table>', response.text, re.DOTALL)
        
        if table_match:
            table_content = table_match.group(1)
            
            # Find all <tr> tags
            rows = re.findall(r'<tr[^>]*>(.*?)</tr>', table_content, re.DOTALL)
            
            print(f"✓ Found {len(rows)} audit log entries")
            
            if rows:
                # Get the first data row (skip header)
                first_row = rows[1] if len(rows) > 1 else rows[0]
                
                # Extract timestamp from first cell
                timestamp_match = re.search(r'<td[^>]*>([^<]+)</td>', first_row)
                
                if timestamp_match:
                    timestamp = timestamp_match.group(1).strip()
                    print(f"\nMost recent audit entry timestamp: {timestamp}")
                    
                    # Check if it contains current Berlin hour
                    berlin_hour = berlin_now.strftime("%H:")
                    utc_hour = utc_now.strftime("%H:")
                    
                    if berlin_hour in timestamp:
                        print(f"✓ Timestamp contains Berlin hour ({berlin_hour})")
                        print("✓ Audit log is using Berlin timezone!")
                    elif utc_hour in timestamp:
                        print(f"✗ Timestamp contains UTC hour ({utc_hour})")
                        print("✗ Audit log is still using UTC")
                        print("\nTo fix this:")
                        print("1. cd ../v2")
                        print("2. docker-compose down")
                        print("3. docker-compose build --no-cache")
                        print("4. docker-compose up -d")
                    else:
                        print("⚠ Could not determine timezone from timestamp")
    else:
        print(f"✗ Failed to fetch audit log: {response.status_code}")

if __name__ == "__main__":
    test_audit_simple()