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

# 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_raw():
    """Test audit log timezone by parsing HTML"""
    session = requests.Session()
    
    print("Audit Log Raw HTML 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')}")
    
    # Logout first
    session.get(f"{base_url_local}/logout", verify=verify_ssl)
    time.sleep(1)
    
    # 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")
    
    # Get audit log
    print("\nFetching audit log...")
    response = session.get(f"{base_url_local}/audit", verify=verify_ssl)
    
    if response.status_code == 200:
        # Save raw HTML for inspection
        with open("audit_log_raw.html", "w", encoding="utf-8") as f:
            f.write(response.text)
        print("✓ Saved raw HTML to audit_log_raw.html")
        
        # Parse with BeautifulSoup
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Find all table rows
        rows = soup.find_all('tr')
        print(f"✓ Found {len(rows)} table rows")
        
        # Look for LOGIN_SUCCESS in recent entries
        for i, row in enumerate(rows[:5]):  # Check first 5 rows
            cells = row.find_all('td')
            if cells and len(cells) > 1:
                timestamp_cell = cells[0].text.strip()
                action_cell = cells[2].text.strip() if len(cells) > 2 else ""
                
                if i == 0:
                    print(f"\nFirst row details:")
                    print(f"  Timestamp: {timestamp_cell}")
                    print(f"  Action: {action_cell}")
                
                if "LOGIN_SUCCESS" in action_cell:
                    print(f"\nFound LOGIN_SUCCESS entry:")
                    print(f"  Timestamp: {timestamp_cell}")
                    
                    # Check if timestamp contains current Berlin hour
                    if berlin_now.strftime("%H:") in timestamp_cell:
                        print(f"  ✓ Contains Berlin hour ({berlin_now.strftime('%H:')})")
                    elif utc_now.strftime("%H:") in timestamp_cell:
                        print(f"  ✗ Contains UTC hour ({utc_now.strftime('%H:')})")
                    break
    else:
        print(f"✗ Failed to fetch audit log: {response.status_code}")

if __name__ == "__main__":
    test_audit_raw()