#!/usr/bin/env python3
"""
Simple HTTP server to serve SPA test page on port 3000
This simulates a Nuxt/Next.js frontend
"""
import http.server
import socketserver
import os
from urllib.parse import urlparse, parse_qs
import json

PORT = 3001  # Using 3001 since 3000 might be in use

class SPAHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Parse URL
        parsed = urlparse(self.path)
        path = parsed.path
        
        # Serve activation page
        if path.startswith('/activate/'):
            parts = path.split('/')
            if len(parts) >= 4:
                uid = parts[2]
                token = parts[3]
                self.serve_activation_page(uid, token)
                return
        
        # Serve main SPA page
        if path == '/' or path == '/index.html':
            self.serve_spa_page()
            return
        
        # Default handler
        super().do_GET()
    
    def serve_spa_page(self):
        """Serve the main SPA page"""
        html = """
<!DOCTYPE html>
<html>
<head>
    <title>Frontend SPA (Port 3000)</title>
    <style>
        body {
            font-family: sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .card {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 { color: #333; }
        .info { background: #e7f3ff; padding: 15px; border-radius: 5px; margin: 20px 0; }
        a { color: #667eea; text-decoration: none; font-weight: bold; }
    </style>
</head>
<body>
    <div class="card">
        <h1>🎉 Frontend SPA (Port 3000)</h1>
        <p>Bu sayfa Nuxt/Next.js frontend'inizi simüle ediyor.</p>
        
        <div class="info">
            <strong>✅ Email activation linkleri buraya gelecek!</strong>
            <p>Format: <code>http://localhost:3000/activate/{uid}/{token}/</code></p>
        </div>
        
        <h3>Test için:</h3>
        <ul>
            <li>Backend'de user oluşturun</li>
            <li>MailPit'te email'i açın</li>
            <li>Activation link'e tıklayın</li>
            <li>Bu sayfaya gelecek ve otomatik activate edecek!</li>
        </ul>
        
        <p><a href="http://localhost:8000/api/v1/spa/">Backend SPA Test (Port 8000)</a></p>
    </div>
</body>
</html>
        """
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(html.encode())
    
    def serve_activation_page(self, uid, token):
        """Serve activation page that calls Django API"""
        html = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Activating Account...</title>
    <style>
        body {{
            font-family: sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }}
        .card {{
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            text-align: center;
        }}
        .spinner {{
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }}
        @keyframes spin {{
            0% {{ transform: rotate(0deg); }}
            100% {{ transform: rotate(360deg); }}
        }}
        .success {{ display: none; color: #28a745; }}
        .error {{ display: none; color: #dc3545; }}
        .icon {{ font-size: 64px; margin-bottom: 20px; }}
        .btn {{
            display: inline-block;
            padding: 12px 30px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            margin-top: 20px;
        }}
    </style>
</head>
<body>
    <div class="card">
        <div id="loading">
            <div class="spinner"></div>
            <h1>Activating Your Account...</h1>
            <p>Please wait...</p>
        </div>
        
        <div id="success" class="success">
            <div class="icon">✅</div>
            <h1>Account Activated!</h1>
            <p>Your account has been successfully activated.</p>
            <a href="http://localhost:8000/api/v1/spa/" class="btn">Go to Login</a>
        </div>
        
        <div id="error" class="error">
            <div class="icon">❌</div>
            <h1>Activation Failed</h1>
            <p id="errorMsg">Something went wrong.</p>
            <a href="http://localhost:8000/api/v1/spa/" class="btn">Back to Login</a>
        </div>
    </div>
    
    <script>
        const uid = '{uid}';
        const token = '{token}';
        
        console.log('Frontend (port 3000) - Activating:', {{ uid, token }});
        
        // Call Django backend API
        fetch('http://localhost:8000/api/v1/auth/users/activation/', {{
            method: 'POST',
            headers: {{
                'Content-Type': 'application/json',
            }},
            body: JSON.stringify({{ uid, token }})
        }})
        .then(response => {{
            console.log('Backend response status:', response.status);
            document.getElementById('loading').style.display = 'none';
            
            if (response.ok || response.status === 204) {{
                document.getElementById('success').style.display = 'block';
                console.log('✅ Activation successful!');
            }} else {{
                return response.json().then(data => {{
                    throw new Error(data.detail || data.token?.[0] || 'Activation failed');
                }});
            }}
        }})
        .catch(error => {{
            console.error('Activation error:', error);
            document.getElementById('loading').style.display = 'none';
            document.getElementById('error').style.display = 'block';
            document.getElementById('errorMsg').textContent = error.message;
        }});
    </script>
</body>
</html>
        """
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(html.encode())

os.chdir('/home/beyhan/Python/server')

with socketserver.TCPServer(("", PORT), SPAHandler) as httpd:
    print(f"🚀 Frontend SPA Server running on http://localhost:{PORT}")
    print(f"📧 Email activation links will work here!")
    print(f"🔗 Open: http://localhost:{PORT}")
    print(f"\nPress Ctrl+C to stop")
    httpd.serve_forever()

