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

# 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 test_session_table():
    """Test if session table exists and structure"""
    print("1. Checking Session Table Structure:")
    print("-" * 40)
    
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
        "-c", "\\d sessions"
    ], capture_output=True, text=True)
    
    if "Table \"public.sessions\"" in result.stdout:
        print("✓ Sessions table exists")
        print("\nTable structure:")
        print(result.stdout)
    else:
        print("✗ Sessions table not found")
        return False
    
    # Check if table is empty
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", "SELECT COUNT(*) FROM sessions;"
    ], capture_output=True, text=True)
    
    count = int(result.stdout.strip())
    print(f"\nCurrent session count: {count}")
    if count == 0:
        print("✓ Session table is empty (as expected - License Server not implemented)")
    
    return True

def test_session_page():
    """Test the sessions management page"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    print("\n2. Testing Sessions Page:")
    print("-" * 40)
    
    response = session.get(f"{base_url}/sessions", verify=False)
    
    if response.status_code == 200:
        print("✓ Sessions page accessible")
        
        content = response.text
        
        # Check for expected elements
        checks = [
            ("Aktive Sessions", "Active sessions section"),
            ("Letzte Sessions", "Recent sessions section"),
            ("IP-Adresse", "IP address column"),
            ("User Agent", "User agent column"),
            ("Heartbeat", "Heartbeat info"),
            ("Session beenden", "End session button")
        ]
        
        for check_text, description in checks:
            if check_text in content:
                print(f"✓ Found: {description}")
            else:
                print(f"✗ Missing: {description}")
        
        # Check for empty state
        if "Keine aktiven Sessions" in content:
            print("✓ Shows empty state for active sessions")
        
    else:
        print(f"✗ Failed to access sessions page: Status {response.status_code}")

def test_dashboard_session_count():
    """Test if dashboard shows session count"""
    session = requests.Session()
    
    if not login(session):
        return "✗ Failed to login"
    
    print("\n3. Testing Dashboard Session Counter:")
    print("-" * 40)
    
    response = session.get(f"{base_url}/", verify=False)
    
    if response.status_code == 200:
        content = response.text
        
        if "Aktive Sessions" in content or "sessions" in content.lower():
            print("✓ Dashboard shows session information")
            
            # Check if it shows 0
            if "0" in content:
                print("✓ Shows 0 active sessions (correct)")
        else:
            print("✗ No session information on dashboard")

def simulate_session_data():
    """Add test session data directly to database"""
    print("\n4. Simulating Session Data:")
    print("-" * 40)
    
    # Get a license ID
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank", "-t",
        "-c", "SELECT id FROM licenses WHERE is_active = TRUE LIMIT 1;"
    ], capture_output=True, text=True)
    
    license_id = result.stdout.strip()
    if not license_id:
        print("✗ No active license found for test")
        return
    
    # Insert test sessions
    test_sessions = [
        # Active session
        f"""INSERT INTO sessions (license_id, session_id, ip_address, user_agent, is_active) 
            VALUES ({license_id}, 'TEST-SESSION-001', '192.168.1.100', 
                   'Mozilla/5.0 Test Browser', TRUE);""",
        
        # Inactive session from today
        f"""INSERT INTO sessions (license_id, session_id, ip_address, user_agent, 
                                started_at, ended_at, is_active) 
            VALUES ({license_id}, 'TEST-SESSION-002', '10.0.0.50', 
                   'Chrome/120.0 Windows', 
                   NOW() - INTERVAL '2 hours', NOW() - INTERVAL '1 hour', FALSE);"""
    ]
    
    for sql in test_sessions:
        result = subprocess.run([
            "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
            "-c", sql
        ], capture_output=True, text=True)
        
        if "INSERT" in result.stdout:
            print("✓ Test session inserted")
        else:
            print("✗ Failed to insert test session")
    
    # Verify
    result = subprocess.run([
        "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
        "-c", "SELECT COUNT(*) as total, COUNT(CASE WHEN is_active THEN 1 END) as active FROM sessions;"
    ], capture_output=True, text=True)
    print("\nSession count after simulation:")
    print(result.stdout)

# Main execution
print("Testing Session Management Features")
print("=" * 50)

# Rebuild admin panel
print("Rebuilding admin panel with session features...")
subprocess.run(["docker-compose", "build", "admin-panel"], capture_output=True)
subprocess.run(["docker-compose", "up", "-d"], capture_output=True)
subprocess.run(["sleep", "5"], capture_output=True)

# Run tests
test_session_table()
test_session_page()
test_dashboard_session_count()
simulate_session_data()

# Test again with data
print("\n5. Re-testing with simulated data:")
print("-" * 40)
test_session_page()

# Cleanup test data
print("\n6. Cleaning up test data:")
subprocess.run([
    "docker", "exec", "db", "psql", "-U", "adminuser", "-d", "meinedatenbank",
    "-c", "DELETE FROM sessions WHERE session_id LIKE 'TEST-%';"
], capture_output=True, text=True)
print("✓ Test sessions removed")