#!/usr/bin/env python3
import requests
import urllib3

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

# Test configuration
base_url = "https://localhost:443"
admin_user = {"username": "rac00n", "password": "1248163264"}

def test_license_overview():
    """Test the new license overview page"""
    session = requests.Session()
    
    # Login first
    login_data = {
        "username": admin_user["username"],
        "password": admin_user["password"]
    }
    
    response = session.post(f"{base_url}/login", data=login_data, verify=False, allow_redirects=False)
    if response.status_code != 302:
        return "Failed to login"
    
    # Access the licenses page
    response = session.get(f"{base_url}/licenses", verify=False)
    
    if response.status_code == 200:
        content = response.text
        
        # Check if we have the expected licenses
        test_results = []
        
        # Check for previously created licenses
        if "Müller GmbH & Co. KG" in content:
            test_results.append("✓ Found: Müller GmbH & Co. KG")
        else:
            test_results.append("✗ Missing: Müller GmbH & Co. KG")
            
        if "Schröder Süßwaren AG" in content:
            test_results.append("✓ Found: Schröder Süßwaren AG")
        else:
            test_results.append("✗ Missing: Schröder Süßwaren AG")
            
        if "Björn Köhler Einzelunternehmen" in content:
            test_results.append("✓ Found: Björn Köhler Einzelunternehmen")
        else:
            test_results.append("✗ Missing: Björn Köhler Einzelunternehmen")
        
        # Check for license status indicators
        if "aktiv" in content or "abgelaufen" in content or "läuft bald ab" in content:
            test_results.append("✓ Status indicators found")
        else:
            test_results.append("✗ No status indicators found")
            
        # Check for UTF-8 characters
        if "ä" in content or "ö" in content or "ü" in content or "ß" in content:
            test_results.append("✓ UTF-8 characters displayed correctly")
        else:
            test_results.append("✗ No UTF-8 characters found")
            
        return test_results, response.status_code
    else:
        return [f"✗ Failed to access licenses page: Status {response.status_code}"], response.status_code

print("Testing License Overview Page")
print("=" * 50)

# First restart admin panel to get the new code
print("Restarting admin panel container...")
import subprocess
subprocess.run(["docker", "restart", "admin-panel"], capture_output=True)
print("Waiting for container to start...")
subprocess.run(["sleep", "5"], capture_output=True)

results, status_code = test_license_overview()

print(f"\nAccessing /licenses endpoint - Status Code: {status_code}")
print("-" * 50)

for result in results:
    print(result)

print("\n" + "=" * 50)
print("Database content check:")
print("-" * 50)

# Check what's actually in the database
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", """SELECT l.id, l.license_key, c.name, l.license_type, 
               l.valid_until,
               CASE 
                   WHEN l.valid_until < CURRENT_DATE THEN 'abgelaufen'
                   WHEN l.valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'läuft bald ab'
                   ELSE 'aktiv'
               END as status
        FROM licenses l
        JOIN customers c ON l.customer_id = c.id
        ORDER BY l.id DESC LIMIT 5;"""
], capture_output=True, text=True)

print(result.stdout)