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

# 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 login(session):
    """Login to admin panel"""
    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)
    return response.status_code == 302

def test_dashboard():
    """Test dashboard with statistics"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    response = session.get(f"{base_url}/", verify=False)
    if response.status_code != 200:
        return f"✗ Failed to access dashboard: Status {response.status_code}"
    
    content = response.text
    results = []
    
    # Check for statistics elements
    statistics_checks = [
        ("Gesamtkunden", "Total customers statistic"),
        ("Gesamtlizenzen", "Total licenses statistic"),
        ("Aktive Lizenzen", "Active licenses statistic"),
        ("Abgelaufene Lizenzen", "Expired licenses statistic"),
        ("Läuft bald ab", "Expiring soon statistic"),
        ("Letzte Lizenzen", "Recent licenses section"),
        ("Bald ablaufende Lizenzen", "Expiring licenses section")
    ]
    
    for check_text, description in statistics_checks:
        if check_text in content:
            results.append(f"✓ Found: {description}")
        else:
            results.append(f"✗ Missing: {description}")
    
    # Check if actual numbers are displayed
    if any(char.isdigit() for char in content):
        results.append("✓ Statistics numbers are displayed")
    else:
        results.append("✗ No statistics numbers found")
    
    # Check for customer names in recent licenses
    if "Müller" in content or "Schröder" in content or "Köhler" in content:
        results.append("✓ Recent licenses show customer names")
    else:
        results.append("✗ No customer names in recent licenses")
    
    return results

# Rebuild and restart admin panel
print("Rebuilding admin panel with dashboard...")
subprocess.run(["docker-compose", "build", "admin-panel"], capture_output=True)
subprocess.run(["docker-compose", "up", "-d", "admin-panel"], capture_output=True)
print("Waiting for container to start...")
subprocess.run(["sleep", "5"], capture_output=True)

print("\nTesting Dashboard with Statistics")
print("=" * 50)

results = test_dashboard()
for result in results:
    print(result)

# Get actual statistics from database for comparison
print("\n" + "=" * 50)
print("Actual Database Statistics:")
print("-" * 50)

# Total customers
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", "SELECT COUNT(*) FROM customers;"
], capture_output=True, text=True)
print(f"Total Customers: {result.stdout.strip()}")

# Total licenses
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", "SELECT COUNT(*) FROM licenses;"
], capture_output=True, text=True)
print(f"Total Licenses: {result.stdout.strip()}")

# Active licenses
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", "SELECT COUNT(*) FROM licenses WHERE valid_until >= CURRENT_DATE AND is_active = TRUE;"
], capture_output=True, text=True)
print(f"Active Licenses: {result.stdout.strip()}")

# Expired licenses
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", "SELECT COUNT(*) FROM licenses WHERE valid_until < CURRENT_DATE;"
], capture_output=True, text=True)
print(f"Expired Licenses: {result.stdout.strip()}")

# Expiring soon (30 days)
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", "SELECT COUNT(*) FROM licenses WHERE valid_until >= CURRENT_DATE AND valid_until < CURRENT_DATE + INTERVAL '30 days' AND is_active = TRUE;"
], capture_output=True, text=True)
print(f"Expiring Soon (30 days): {result.stdout.strip()}")

# License types breakdown
print("\nLicense Types:")
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", "SELECT license_type, COUNT(*) FROM licenses GROUP BY license_type ORDER BY COUNT(*) DESC;"
], capture_output=True, text=True)
print(result.stdout)

# Recent licenses
print("Recent Licenses:")
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", """SELECT l.license_key, c.name, 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)