"""
NEXUS Web Interface Module
Modern web interface for OSINT investigations
"""

import asyncio
import json
import os
from datetime import datetime
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import CORS
import threading
import webbrowser
from colorama import Fore, Style
import time

# Import NEXUS modules
from modules.username_search import UsernameSearcher
from modules.web_scraper import WebScraper
from modules.email_investigator import EmailInvestigator
from modules.domain_analyzer import DomainAnalyzer
from modules.ip_analyzer import IPAnalyzer

class NEXUSWebInterface:
    """Web interface for NEXUS OSINT Tool"""
    
    def __init__(self):
        self.app = Flask(__name__, template_folder='../templates', static_folder='../static')
        CORS(self.app)
        self.port = 5000
        self.host = '127.0.0.1'
        
        # Initialize OSINT modules
        self.username_searcher = UsernameSearcher()
        self.web_scraper = WebScraper()
        self.email_investigator = EmailInvestigator()
        self.domain_analyzer = DomainAnalyzer()
        self.ip_analyzer = IPAnalyzer()
        
        # Setup routes
        self.setup_routes()
        
    def setup_routes(self):
        """Setup Flask routes"""
        
        @self.app.route('/')
        def index():
            """Main dashboard page"""
            return render_template('index.html')
        
        @self.app.route('/api/investigate', methods=['POST'])
        def investigate():
            """Handle investigation requests"""
            try:
                data = request.get_json()
                investigation_type = data.get('type')
                target = data.get('target')
                
                if not investigation_type or not target:
                    return jsonify({'error': 'Missing investigation type or target'}), 400
                
                # Run investigation asynchronously
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                
                if investigation_type == 'username':
                    results = loop.run_until_complete(self.username_searcher.search([target]))
                elif investigation_type == 'email':
                    results = loop.run_until_complete(self.email_investigator.investigate(target))
                elif investigation_type == 'domain':
                    results = loop.run_until_complete(self.domain_analyzer.analyze(target))
                elif investigation_type == 'ip':
                    results = loop.run_until_complete(self.ip_analyzer.analyze(target))
                elif investigation_type == 'scrape':
                    results = loop.run_until_complete(self.web_scraper.scrape_url(target))
                else:
                    return jsonify({'error': 'Invalid investigation type'}), 400
                
                loop.close()
                
                # Format results for web display
                formatted_results = self.format_results(results, investigation_type, target)
                
                return jsonify({
                    'success': True,
                    'results': formatted_results,
                    'timestamp': datetime.now().isoformat()
                })
                
            except Exception as e:
                return jsonify({'error': str(e)}), 500
        
        @self.app.route('/api/status')
        def status():
            """Get tool status"""
            return jsonify({
                'status': 'running',
                'modules': {
                    'username_search': 'active',
                    'email_investigator': 'active',
                    'domain_analyzer': 'active',
                    'ip_analyzer': 'active',
                    'web_scraper': 'active'
                },
                'version': '2.0.0'
            })
        
        @self.app.route('/static/<path:filename>')
        def static_files(filename):
            """Serve static files"""
            return send_from_directory('../static', filename)
    
    def format_results(self, results, investigation_type, target):
        """Format results for web display"""
        formatted = {
            'type': investigation_type,
            'target': target,
            'timestamp': datetime.now().isoformat(),
            'data': results
        }
        
        # Add specific formatting based on investigation type
        if investigation_type == 'username':
            # Handle username search results which are in a dict format
            if isinstance(results, dict) and target in results:
                user_result = results[target]
                formatted['summary'] = {
                    'found_accounts': len(user_result.get('found_accounts', [])),
                    'total_sites': user_result.get('total_checked', 0),
                    'confidence': 'High' if user_result.get('found_accounts') else 'Low'
                }
            else:
                formatted['summary'] = {
                    'found_accounts': 0,
                    'total_sites': 0,
                    'confidence': 'Unknown'
                }
        elif investigation_type == 'scrape':
            formatted['summary'] = {
                'title': results.get('title', 'No title'),
                'links_found': len(results.get('content', {}).get('links', [])),
                'images_found': len(results.get('content', {}).get('images', [])),
                'ai_summary': results.get('ai_summary', {})
            }
        elif investigation_type == 'email':
            summary = results.get('summary', {})
            formatted['summary'] = {
                'provider': summary.get('provider', 'Unknown'),
                'verification_score': summary.get('verification_score', 0),
                'risk_level': summary.get('risk_level', 'Unknown'),
                'breached': summary.get('breached', False)
            }
        elif investigation_type == 'domain':
            summary = results.get('summary', {})
            formatted['summary'] = {
                'registrar': summary.get('registrar', 'Unknown'),
                'domain_age': summary.get('domain_age', 'Unknown'),
                'security_score': summary.get('security_score', 'Unknown'),
                'ssl_valid': summary.get('ssl_valid', False)
            }
        elif investigation_type == 'ip':
            summary = results.get('summary', {})
            formatted['summary'] = {
                'location': f"{summary.get('city', 'Unknown')}, {summary.get('country', 'Unknown')}",
                'isp': summary.get('isp', 'Unknown'),
                'overall_risk': summary.get('overall_risk', 'Unknown'),
                'open_ports': summary.get('open_ports_count', 0)
            }
        
        return formatted
    
    def run_server(self):
        """Run the Flask server"""
        print(f"{Fore.GREEN}[+] Starting NEXUS Web Interface...{Style.RESET_ALL}")
        print(f"{Fore.CYAN}[*] Server running on http://{self.host}:{self.port}{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}[!] Press Ctrl+C to stop the server{Style.RESET_ALL}")
        
        # Open browser automatically
        threading.Timer(1.5, lambda: webbrowser.open(f'http://{self.host}:{self.port}')).start()
        
        try:
            self.app.run(host=self.host, port=self.port, debug=False)
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}[!] Web interface stopped by user{Style.RESET_ALL}")

def create_templates():
    """Create HTML templates"""
    templates_dir = '../templates'
    static_dir = '../static'
    
    # Create directories
    os.makedirs(templates_dir, exist_ok=True)
    os.makedirs(static_dir, exist_ok=True)
    
    # Create main template
    index_html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NEXUS OSINT Tool - Web Interface</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 40px;
            color: white;
        }
        
        h1 {
            font-size: 3em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .main-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 30px;
        }
        
        .investigation-form {
            display: grid;
            gap: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        label {
            font-weight: 600;
            color: #555;
        }
        
        select, input[type="text"], input[type="url"] {
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        select:focus, input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .results {
            margin-top: 30px;
        }
        
        .result-card {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .status {
            background: #e8f5e8;
            border: 1px solid #4caf50;
            color: #2e7d32;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🔍 NEXUS OSINT</h1>
            <p class="subtitle">Comprehensive Investigation Tool - Web Interface</p>
        </header>
        
        <div class="main-card">
            <div class="status" id="status">
                ✅ All modules active and ready
            </div>
            
            <form class="investigation-form" id="investigationForm">
                <div class="form-group">
                    <label for="investigationType">Investigation Type</label>
                    <select id="investigationType" required>
                        <option value="">Select investigation type...</option>
                        <option value="username">Username Search</option>
                        <option value="email">Email Investigation</option>
                        <option value="domain">Domain Analysis</option>
                        <option value="ip">IP Analysis</option>
                        <option value="scrape">Web Scraping</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="target">Target</label>
                    <input type="text" id="target" placeholder="Enter username, email, domain, IP, or URL..." required>
                </div>
                
                <button type="submit" class="btn" id="investigateBtn">
                    🚀 Start Investigation
                </button>
            </form>
            
            <div class="results" id="results"></div>
        </div>
    </div>
    
    <script>
        const form = document.getElementById('investigationForm');
        const resultsDiv = document.getElementById('results');
        const investigateBtn = document.getElementById('investigateBtn');
        
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const type = document.getElementById('investigationType').value;
            const target = document.getElementById('target').value;
            
            if (!type || !target) {
                alert('Please fill in all fields');
                return;
            }
            
            // Show loading
            investigateBtn.disabled = true;
            investigateBtn.innerHTML = '🔄 Investigating...';
            resultsDiv.innerHTML = `
                <div class="loading">
                    <div class="spinner"></div>
                    <p>Investigating ${type} for "${target}"...</p>
                </div>
            `;
            
            try {
                const response = await fetch('/api/investigate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ type, target })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    displayResults(data.results);
                } else {
                    throw new Error(data.error || 'Investigation failed');
                }
            } catch (error) {
                resultsDiv.innerHTML = `
                    <div class="result-card">
                        <h3>❌ Error</h3>
                        <p>${error.message}</p>
                    </div>
                `;
            } finally {
                investigateBtn.disabled = false;
                investigateBtn.innerHTML = '🚀 Start Investigation';
            }
        });
        
        function displayResults(results) {
            const html = `
                <div class="result-card">
                    <h3>🔍 Investigation Results</h3>
                    <p><strong>Type:</strong> ${results.type}</p>
                    <p><strong>Target:</strong> ${results.target}</p>
                    <p><strong>Time:</strong> ${new Date(results.timestamp).toLocaleString()}</p>
                    
                    ${results.summary ? `
                        <h4>📊 Summary</h4>
                        <pre>${JSON.stringify(results.summary, null, 2)}</pre>
                    ` : ''}
                    
                    <h4>📋 Detailed Results</h4>
                    <pre>${JSON.stringify(results.data, null, 2)}</pre>
                </div>
            `;
            
            resultsDiv.innerHTML = html;
        }
        
        // Check status on load
        fetch('/api/status')
            .then(response => response.json())
            .then(data => {
                const statusDiv = document.getElementById('status');
                if (data.status === 'running') {
                    statusDiv.innerHTML = '✅ All modules active and ready';
                } else {
                    statusDiv.innerHTML = '⚠️ Some modules may not be available';
                }
            })
            .catch(error => {
                console.error('Status check failed:', error);
            });
    </script>
</body>
</html>
"""
    
    with open(os.path.join(templates_dir, 'index.html'), 'w', encoding='utf-8') as f:
        f.write(index_html)
    
    print(f"{Fore.GREEN}[+] Created web templates{Style.RESET_ALL}")

if __name__ == "__main__":
    create_templates()
    web_interface = NEXUSWebInterface()
    web_interface.run_server()
