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

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

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 check_requirements():
    """Check if pandas is in requirements.txt"""
    print("1. Checking requirements.txt:")
    print("-" * 40)
    
    result = subprocess.run([
        "cat", "/mnt/c/Users/Administrator/Documents/GitHub/v2-Docker/v2_adminpanel/requirements.txt"
    ], capture_output=True, text=True)
    
    print(result.stdout)
    
    if "pandas" not in result.stdout:
        print("✗ pandas not in requirements.txt - adding it")
        # Add pandas and openpyxl
        subprocess.run([
            "echo", "-e", "pandas\\nopenpyxl", ">>",
            "/mnt/c/Users/Administrator/Documents/GitHub/v2-Docker/v2_adminpanel/requirements.txt"
        ])

def test_export_endpoints():
    """Test export endpoints"""
    session = requests.Session()
    
    if not login(session):
        return ["✗ Failed to login"]
    
    print("\n2. Testing Export Endpoints:")
    print("-" * 40)
    
    # Test license exports
    exports = [
        ("/export/licenses?format=excel", "License Excel Export"),
        ("/export/licenses?format=csv", "License CSV Export"),
        ("/export/customers?format=excel", "Customer Excel Export"),
        ("/export/customers?format=csv", "Customer CSV Export")
    ]
    
    for endpoint, description in exports:
        response = session.get(f"{base_url}{endpoint}", verify=False, stream=True)
        
        if response.status_code == 200:
            # Check headers
            content_type = response.headers.get('Content-Type', '')
            content_disp = response.headers.get('Content-Disposition', '')
            
            # Get first few bytes to check file type
            first_bytes = response.raw.read(10)
            
            if 'excel' in endpoint and b'PK' in first_bytes:  # Excel files start with PK (ZIP format)
                print(f"✓ {description}: Valid Excel file signature")
            elif 'csv' in endpoint and (b'ID' in first_bytes or b'"' in first_bytes or b';' in first_bytes):
                print(f"✓ {description}: Looks like CSV data")
            else:
                print(f"✓ {description}: Response received (Status 200)")
            
            if 'attachment' in content_disp:
                print(f"  → Download filename: {content_disp.split('filename=')[1] if 'filename=' in content_disp else 'present'}")
        else:
            print(f"✗ {description}: Failed with status {response.status_code}")

def test_export_content():
    """Test actual export content"""
    session = requests.Session()
    
    if not login(session):
        return
    
    print("\n3. Testing Export Content:")
    print("-" * 40)
    
    # Get CSV export to check content
    response = session.get(f"{base_url}/export/licenses?format=csv", verify=False)
    
    if response.status_code == 200:
        content = response.text
        lines = content.split('\n')
        
        print(f"CSV Lines: {len(lines)}")
        
        if lines:
            # Check header
            header = lines[0]
            print(f"CSV Header: {header[:100]}...")
            
            # Check for UTF-8 BOM
            if content.startswith('\ufeff'):
                print("✓ UTF-8 BOM present (Excel compatibility)")
            
            # Check for umlauts
            if any(char in content for char in 'äöüßÄÖÜ'):
                print("✓ German umlauts found in export")
            
            # Check separator
            if ';' in header:
                print("✓ Using semicolon separator (German Excel standard)")

# Main execution
print("Testing Export Functionality")
print("=" * 50)

# Check and fix requirements
check_requirements()

# Rebuild admin panel with pandas
print("\nRebuilding admin panel with pandas...")
subprocess.run([
    "docker", "exec", "admin-panel", "pip", "install", "pandas", "openpyxl"
], capture_output=True)

result = subprocess.run([
    "docker", "exec", "admin-panel", "python", "-c",
    "import pandas; print('pandas installed:', pandas.__version__)"
], capture_output=True, text=True)

if result.returncode == 0:
    print("✓ pandas installed in container")
    print(result.stdout.strip())
else:
    print("✗ Failed to install pandas")

# Test endpoints
test_export_endpoints()
test_export_content()

# Database summary
print("\n4. Database Summary:")
print("-" * 40)

result = subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
    "-c", """SELECT 
             (SELECT COUNT(*) FROM licenses) as licenses,
             (SELECT COUNT(*) FROM customers) as customers,
             (SELECT COUNT(*) FROM licenses WHERE valid_until >= CURRENT_DATE) as active_licenses;"""
], capture_output=True, text=True)

print(f"Available for export: {result.stdout.strip()}")