#!/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_license_search():
    """Test license search functionality"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    test_cases = [
        # (search_term, expected_results, description)
        ("müller", ["Müller GmbH & Co. KG"], "Search by customer name with umlaut"),
        ("KÖHLER", ["Björn Köhler"], "Search by license key (case insensitive)"),
        ("@übersetzungen.de", ["Björn Köhler"], "Search by email domain with umlaut"),
        ("2025", ["KÖHLER-2025", "MÜLLER-2025", "SCHRÖDER-2025"], "Search by year in license key"),
        ("premium", ["TEST-LICENSE-KEY"], "Search by license type"),
        ("süßwaren", ["Schröder Süßwaren"], "Search with special characters"),
        ("xyz123", [], "Search with no results")
    ]
    
    results = []
    
    for search_term, expected, description in test_cases:
        response = session.get(f"{base_url}/licenses?search={search_term}", verify=False)
        
        if response.status_code != 200:
            results.append(f"✗ {description}: Failed with status {response.status_code}")
            continue
        
        content = response.text
        found = []
        
        for expected_item in expected:
            if expected_item.lower() in content.lower():
                found.append(expected_item)
        
        if len(found) == len(expected) and len(expected) > 0:
            results.append(f"✓ {description}: Found {len(found)} result(s)")
        elif len(expected) == 0 and "Keine Lizenzen gefunden" in content:
            results.append(f"✓ {description}: Correctly shows no results")
        else:
            results.append(f"✗ {description}: Expected {len(expected)}, found {len(found)}")
    
    return results

def test_customer_search():
    """Test customer search functionality"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    test_cases = [
        # (search_term, expected_results, description)
        ("gmbh", ["Müller GmbH", "Schröder", "Test Customer GmbH", "Löschtest"], "Search for GmbH companies"),
        ("björn", ["Björn Köhler"], "Search by first name with umlaut"),
        ("@müller", ["Müller GmbH & Co. KG"], "Search by email with umlaut"),
        ("test", ["Test Customer", "Testfirma", "Löschtest"], "Search for test entries"),
        ("überprüfung", ["Testfirma für Umlaute"], "Search with umlaut in term"),
        ("nonexistent", [], "Search with no results")
    ]
    
    results = []
    
    for search_term, expected, description in test_cases:
        response = session.get(f"{base_url}/customers?search={search_term}", verify=False)
        
        if response.status_code != 200:
            results.append(f"✗ {description}: Failed with status {response.status_code}")
            continue
        
        content = response.text
        found = []
        
        for expected_item in expected:
            if expected_item.lower() in content.lower():
                found.append(expected_item)
        
        if len(found) >= len(expected) * 0.7:  # Allow 70% match rate due to variations
            results.append(f"✓ {description}: Found {len(found)} result(s)")
        else:
            results.append(f"✗ {description}: Expected ~{len(expected)}, found {len(found)}")
    
    return results

# Rebuild and restart admin panel
print("Rebuilding admin panel with search functionality...")
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 Search Functionality")
print("=" * 50)

# Test license search
print("\n1. License Search Tests:")
print("-" * 30)
license_results = test_license_search()
for result in license_results:
    print(result)

# Test customer search
print("\n2. Customer Search Tests:")
print("-" * 30)
customer_results = test_customer_search()
for result in customer_results:
    print(result)

# Show some example search results from database
print("\n" + "=" * 50)
print("Database Search Examples:")
print("-" * 50)

# Example: Search for "müller" in licenses
print("\nSearching for 'müller' in licenses:")
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", """SELECT l.license_key, c.name, c.email 
             FROM licenses l 
             JOIN customers c ON l.customer_id = c.id
             WHERE LOWER(c.name) LIKE LOWER('%müller%')
                OR LOWER(l.license_key) LIKE LOWER('%müller%')
                OR LOWER(c.email) LIKE LOWER('%müller%');"""
], capture_output=True, text=True)
print(result.stdout)

# Example: Search for customers with "test"
print("Searching for 'test' in customers:")
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", """SELECT name, email 
             FROM customers 
             WHERE LOWER(name) LIKE LOWER('%test%')
                OR LOWER(email) LIKE LOWER('%test%');"""
], capture_output=True, text=True)
print(result.stdout)