#!/usr/bin/env python3
import requests
import urllib3
import subprocess
from datetime import datetime, timedelta

# 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 create_test_data():
    """Create additional test data for pagination testing"""
    session = requests.Session()
    if not login(session):
        return False
    
    # Create 25 test licenses to test pagination (20 per page)
    for i in range(25):
        license_data = {
            "customer_name": f"Pagination Test {i+1}",
            "email": f"page{i+1}@test.de",
            "license_key": f"PAGE-TEST-{i+1:03d}",
            "license_type": "test" if i % 3 == 0 else "full",
            "valid_from": "2025-01-01",
            "valid_until": (datetime.now() + timedelta(days=i*10)).strftime("%Y-%m-%d") if i % 2 == 0 else "2024-12-31"
        }
        session.post(f"{base_url}/create", data=license_data, verify=False, allow_redirects=False)
    
    return True

def test_license_filters():
    """Test license filtering functionality"""
    session = requests.Session()
    
    if not login(session):
        return ["✗ Failed to login"]
    
    results = []
    
    # Test type filters
    filter_tests = [
        ("type=test", "Filter by type 'test'"),
        ("type=full", "Filter by type 'full'"),
        ("status=active", "Filter by active status"),
        ("status=expired", "Filter by expired status"),
        ("status=expiring", "Filter by expiring soon"),
        ("type=test&status=active", "Combined filter: test + active"),
        ("search=page&type=test", "Search + type filter"),
        ("search=müller&status=active", "Search with umlaut + status filter")
    ]
    
    for filter_param, description in filter_tests:
        response = session.get(f"{base_url}/licenses?{filter_param}", verify=False)
        
        if response.status_code == 200:
            content = response.text
            # Check if results are shown (not "Keine Lizenzen gefunden")
            if "license_key" in content or "Keine Lizenzen gefunden" in content:
                results.append(f"✓ {description}: Filter applied successfully")
            else:
                results.append(f"✗ {description}: No results section found")
        else:
            results.append(f"✗ {description}: Failed with status {response.status_code}")
    
    return results

def test_pagination():
    """Test pagination functionality"""
    session = requests.Session()
    
    if not login(session):
        return ["✗ Failed to login"]
    
    results = []
    
    # Test licenses pagination
    response = session.get(f"{base_url}/licenses", verify=False)
    if response.status_code == 200:
        content = response.text
        
        # Check for pagination elements
        if "page=" in content:
            results.append("✓ Pagination links present in licenses")
        else:
            results.append("✗ No pagination links in licenses")
        
        # Check page 2
        response2 = session.get(f"{base_url}/licenses?page=2", verify=False)
        if response2.status_code == 200:
            content2 = response2.text
            if content != content2:  # Different content on different pages
                results.append("✓ Page 2 shows different content")
            else:
                results.append("✗ Page 2 shows same content as page 1")
        
        # Check for total count display
        if "von" in content and "Einträgen" in content:
            results.append("✓ Total entries count displayed")
        else:
            results.append("✗ Total entries count not displayed")
    
    # Test customers pagination
    response = session.get(f"{base_url}/customers", verify=False)
    if response.status_code == 200:
        content = response.text
        if "page=" in content or "Seite" in content:
            results.append("✓ Pagination present in customers")
        else:
            results.append("✗ No pagination in customers")
    
    return results

def test_pagination_with_filters():
    """Test pagination combined with filters"""
    session = requests.Session()
    
    if not login(session):
        return ["✗ Failed to login"]
    
    results = []
    
    # Test pagination preserves filters
    test_urls = [
        (f"{base_url}/licenses?type=test&page=2", "Pagination with type filter"),
        (f"{base_url}/licenses?search=page&page=2", "Pagination with search"),
        (f"{base_url}/licenses?status=active&type=full&page=1", "Multiple filters with pagination"),
        (f"{base_url}/customers?search=test&page=2", "Customer search with pagination")
    ]
    
    for test_url, description in test_urls:
        response = session.get(test_url, verify=False)
        if response.status_code == 200:
            content = response.text
            # Check if filters are preserved in pagination links
            if "type=" in test_url and "type=" in content:
                results.append(f"✓ {description}: Filters preserved")
            elif "search=" in test_url and "search=" in content:
                results.append(f"✓ {description}: Search preserved")
            else:
                results.append(f"✓ {description}: Page loaded")
        else:
            results.append(f"✗ {description}: Failed")
    
    return results

# Setup
print("Setting up test environment...")
subprocess.run(["docker-compose", "build", "admin-panel"], capture_output=True)
subprocess.run(["docker-compose", "up", "-d", "admin-panel"], capture_output=True)
subprocess.run(["sleep", "5"], capture_output=True)

print("\nCreating test data for pagination...")
if create_test_data():
    print("✓ Test data created")
else:
    print("✗ Failed to create test data")

print("\nTesting Filter and Pagination Functionality")
print("=" * 50)

# Test filters
print("\n1. License Filter Tests:")
print("-" * 30)
filter_results = test_license_filters()
for result in filter_results:
    print(result)

# Test pagination
print("\n2. Pagination Tests:")
print("-" * 30)
pagination_results = test_pagination()
for result in pagination_results:
    print(result)

# Test combined
print("\n3. Combined Filter + Pagination Tests:")
print("-" * 30)
combined_results = test_pagination_with_filters()
for result in combined_results:
    print(result)

# Database statistics
print("\n" + "=" * 50)
print("Database Statistics after Tests:")
print("-" * 50)

# License type distribution
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("License Types:")
print(result.stdout)

# Status distribution
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", """SELECT 
             CASE 
                 WHEN valid_until < CURRENT_DATE THEN 'expired'
                 WHEN valid_until < CURRENT_DATE + INTERVAL '30 days' THEN 'expiring'
                 ELSE 'active'
             END as status,
             COUNT(*)
             FROM licenses
             GROUP BY status
             ORDER BY COUNT(*) DESC;"""
], capture_output=True, text=True)
print("License Status:")
print(result.stdout)