#!/usr/bin/env python3
"""
Authentication testing and debugging utility for NGON Site Manager
Provides functionality to:
- Check current authentication status
- View authentication cookies
- Clear authentication (logout)
- Test authentication credentials
"""

import cgi
import os
import sys
import json
import http.cookies

# Add the apps directory to Python path for imports
sys.path.insert(0, '/opt/ngon/apps')
from managers.auth_manager import AuthManager

# Enable CGI debugging
import cgitb
cgitb.enable()

# Initialize form handling
form = cgi.FieldStorage()

# Initialize authentication
auth = AuthManager('site_manager')

# Get action from query parameter
action = form.getvalue('action', 'status')

# Handle different actions
print("Content-Type: text/html\n")

print("""
<!DOCTYPE html>
<html>
<head>
    <title>NGON Auth Test Utility</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #1a1a1a;
            color: #e0e0e0;
            margin: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: #2a2a2a;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.5);
        }
        h1 {
            color: #00ff00;
            margin-bottom: 20px;
        }
        .status-box {
            background: #333;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
            border: 1px solid #444;
        }
        .authenticated {
            border-color: #00ff00;
            background: #1a3a1a;
        }
        .not-authenticated {
            border-color: #ff4444;
            background: #3a1a1a;
        }
        .info-label {
            color: #888;
            font-weight: bold;
            display: inline-block;
            width: 150px;
        }
        .info-value {
            color: #fff;
            font-family: monospace;
        }
        .button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 10px 5px;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .button.danger {
            background-color: #dc3545;
        }
        .button.danger:hover {
            background-color: #c82333;
        }
        .button.success {
            background-color: #28a745;
        }
        .button.success:hover {
            background-color: #218838;
        }
        .cookie-details {
            margin-top: 15px;
            padding: 10px;
            background: #222;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .message.success {
            background: #1a3a1a;
            border: 1px solid #00ff00;
            color: #00ff00;
        }
        .message.error {
            background: #3a1a1a;
            border: 1px solid #ff4444;
            color: #ff4444;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>NGON Authentication Test Utility</h1>
""")

# Check authentication status
is_authenticated = auth.is_authenticated()

if action == 'status':
    # Display authentication status
    status_class = 'authenticated' if is_authenticated else 'not-authenticated'
    status_text = 'Authenticated' if is_authenticated else 'Not Authenticated'
    
    print(f'<div class="status-box {status_class}">')
    print(f'<h2>Authentication Status: {status_text}</h2>')
    
    # Show cookie information
    print('<div>')
    print(f'<span class="info-label">Application:</span>')
    print(f'<span class="info-value">{auth.app_name}</span>')
    print('</div>')
    
    print('<div>')
    print(f'<span class="info-label">Cookie Name:</span>')
    print(f'<span class="info-value">{auth.cookie_name}</span>')
    print('</div>')
    
    # Show raw cookie data
    cookie_data = os.environ.get('HTTP_COOKIE', 'No cookies found')
    print('<div>')
    print('<span class="info-label">Raw Cookie Data:</span>')
    print(f'<div class="cookie-details">{cookie_data}</div>')
    print('</div>')
    
    # Parse and show specific auth cookie if present
    try:
        cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE', ''))
        if auth.cookie_name in cookies:
            auth_cookie = cookies[auth.cookie_name]
            print('<div>')
            print(f'<span class="info-label">Auth Token:</span>')
            print(f'<div class="cookie-details">{auth_cookie.value}</div>')
            print('</div>')
    except:
        pass
    
    print('</div>')
    
    # Show available actions
    print('<h3>Available Actions:</h3>')
    print('<div>')
    
    if is_authenticated:
        print('<a href="?action=logout" class="button danger">Logout (Clear Cookie)</a>')
        print('<a href="site_manager.py" class="button success">Go to Site Manager</a>')
    else:
        print('<a href="site_manager.py" class="button">Go to Site Manager (Login Required)</a>')
    
    print('<a href="?action=debug" class="button">Show Debug Info</a>')
    print('</div>')

elif action == 'logout':
    # Clear authentication cookie
    print('<h2>Logout</h2>')
    
    # Create expired cookie to clear it
    cookie = http.cookies.SimpleCookie()
    cookie[auth.cookie_name] = ''
    cookie[auth.cookie_name]['path'] = '/'
    cookie[auth.cookie_name]['max-age'] = 0
    cookie[auth.cookie_name]['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
    
    # Output cookie header to clear it
    print(f'<script>document.cookie = "{auth.cookie_name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";</script>')
    
    print('<div class="message success">Authentication cookie has been cleared. You are now logged out.</div>')
    print('<div>')
    print('<a href="?action=status" class="button">Check Status</a>')
    print('<a href="site_manager.py" class="button">Go to Site Manager</a>')
    print('</div>')

elif action == 'debug':
    # Show detailed debug information
    print('<h2>Debug Information</h2>')
    
    print('<div class="status-box">')
    print('<h3>Environment Variables:</h3>')
    print('<div class="cookie-details">')
    for key, value in sorted(os.environ.items()):
        if any(x in key.upper() for x in ['COOKIE', 'AUTH', 'USER', 'REQUEST', 'HTTP']):
            print(f'{key}: {value}')
    print('</div>')
    print('</div>')
    
    print('<div class="status-box">')
    print('<h3>Authentication Configuration:</h3>')
    print('<div class="cookie-details">')
    print(f'App Name: {auth.app_name}')
    print(f'Cookie Name: {auth.cookie_name}')
    print(f'Credentials File: {auth.credentials_file}')
    
    # Try to load and show credentials (mask password)
    try:
        creds = auth.load_credentials()
        print(f'Username: {creds.get("username", "N/A")}')
        print(f'Password: {"*" * len(creds.get("password", ""))}')
    except Exception as e:
        print(f'Error loading credentials: {e}')
    
    print('</div>')
    print('</div>')
    
    print('<div>')
    print('<a href="?action=status" class="button">Back to Status</a>')
    print('</div>')

else:
    print('<div class="message error">Invalid action specified</div>')
    print('<a href="?action=status" class="button">Go to Status</a>')

print("""
</div>
</body>
</html>
""")