#!/usr/bin/env python3
import requests
import urllib3
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 test_umlaut_support():
    """Test UTF-8 support with German umlauts"""
    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"
    
    # Create test data with German umlauts
    test_customers = [
        {
            "customer_name": "Müller GmbH & Co. KG",
            "email": "kontakt@müller-gmbh.de",
            "license_key": "MÜLLER-2025-ÄÖÜ",
            "license_type": "Premium-Größe",
            "valid_from": datetime.now().strftime("%Y-%m-%d"),
            "valid_until": (datetime.now() + timedelta(days=365)).strftime("%Y-%m-%d")
        },
        {
            "customer_name": "Schröder Süßwaren AG",
            "email": "info@schröder-süßwaren.de",
            "license_key": "SCHRÖDER-2025-ßÄÖÜ",
            "license_type": "Geschäftskunden",
            "valid_from": datetime.now().strftime("%Y-%m-%d"),
            "valid_until": (datetime.now() + timedelta(days=180)).strftime("%Y-%m-%d")
        },
        {
            "customer_name": "Björn Köhler Einzelunternehmen",
            "email": "björn.köhler@übersetzungen.de",
            "license_key": "KÖHLER-2025-BJÖRN",
            "license_type": "Übersetzungsbüro",
            "valid_from": datetime.now().strftime("%Y-%m-%d"),
            "valid_until": (datetime.now() + timedelta(days=90)).strftime("%Y-%m-%d")
        }
    ]
    
    results = []
    for customer in test_customers:
        response = session.post(f"{base_url}/", data=customer, verify=False, allow_redirects=False)
        
        if response.status_code == 302 and response.headers.get('Location') == '/':
            results.append(f"✓ Created: {customer['customer_name']}")
        else:
            results.append(f"✗ Failed: {customer['customer_name']} - Status: {response.status_code}")
    
    return results

print("Testing UTF-8 German Umlaut Support")
print("=" * 50)
print("Creating customers with special characters: ä, ö, ü, ß, Ä, Ö, Ü")
print("-" * 50)

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

# Verify the data in the database
print("\n" + "=" * 50)
print("Verifying database entries:")
print("-" * 50)

import subprocess
result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", "SELECT c.name, c.email, l.license_key, l.license_type FROM licenses l JOIN customers c ON l.customer_id = c.id ORDER BY c.id DESC LIMIT 3;"
], capture_output=True, text=True)

print(result.stdout)

# Test direct database insertion with umlauts
print("Direct database test with umlauts:")
print("-" * 50)

test_query = """
INSERT INTO customers (name, email) VALUES ('Testfirma für Umlaute: äöüßÄÖÜ', 'test@überprüfung.de') RETURNING name, email;
"""

result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", 
    "-c", test_query
], capture_output=True, text=True)

print(result.stdout)