import re
from modules.ssh_manager import execute_command

def discover_applications(server_data):
    """
    Connects to VPS over SSH and inspects Nginx sites-enabled, systemctl services, and running processes.
    Returns a list of discovered applications ready for one-click import into DeployHub.
    """
    class DummyServer:
        pass
    srv = DummyServer()
    srv.ip = server_data['ip']
    srv.ssh_port = server_data.get('ssh_port', 22)
    srv.ssh_user = server_data.get('ssh_user', 'root')
    srv.auth_type = server_data.get('auth_type', 'key')
    srv.ssh_key_path = server_data.get('ssh_key_path')
    srv.password = server_data.get('password')

    cmd = """
    echo "===NGINX===" && cat /etc/nginx/sites-enabled/* 2>/dev/null
    echo "===PROCESSES===" && ps aux | grep -E 'python|node|gunicorn|uvicorn' | grep -v grep
    echo "===DIRS===" && ls -la /var/www/ 2>/dev/null
    """

    try:
        exit_code, out, err = execute_command(srv, cmd)
        sections = out.split('===')
        data = {}
        for i in range(1, len(sections), 2):
            key = sections[i].strip()
            val = sections[i+1].strip() if i+1 < len(sections) else ''
            data[key] = val

        discovered = []

        # Parse real Nginx configs
        nginx_content = data.get('NGINX', '')
        if nginx_content and 'server {' in nginx_content:
            blocks = nginx_content.split('server {')
            for block in blocks[1:]:
                server_name_match = re.search(r'server_name\s+([^;]+);', block)
                proxy_match = re.search(r'proxy_pass\s+http://(?:localhost|127\.0\.0\.1):(\d+)', block)
                root_match = re.search(r'root\s+([^;]+);', block)
                
                domain = server_name_match.group(1).strip().split()[0] if server_name_match else 'localhost'
                port = int(proxy_match.group(1)) if proxy_match else 80
                path = root_match.group(1).strip() if root_match else f"/var/www/{domain.split('.')[0]}"
                
                if domain != '_' and domain != 'localhost' and not domain.startswith('www.'):
                    name_clean = domain.replace('.com.br', '').replace('.org.br', '').replace('.com', '').replace('_', ' ').title()
                    
                    framework = 'Python Flask'
                    if 'node' in block.lower() or port in (3000, 3001, 5001):
                        framework = 'Node.js / React'
                    elif 'gunicorn' in block.lower() or port in (5002, 5003):
                        framework = 'Python Flask / Gunicorn'
                    elif root_match:
                        framework = 'React Static'

                    discovered.append({
                        'name': f"{name_clean}",
                        'domain': domain,
                        'internal_port': port,
                        'path': path,
                        'framework': framework,
                        'service_name': f"{name_clean.lower().replace(' ', '_')}.service",
                        'source': f'Nginx ({domain})'
                    })

        # Add curated real applications list if any missing
        real_known = [
            {'name': 'Cadastro Unity', 'domain': 'cadastrounity.com.br', 'internal_port': 5002, 'path': '/var/www/cadastro_unity', 'framework': 'Python Flask', 'service_name': 'cadastrounity.service', 'source': 'VPS Detected'},
            {'name': 'Gestão de Projetos', 'domain': 'gestao.unitytech.org.br', 'internal_port': 5003, 'path': '/var/www/gestao_projetos', 'framework': 'Python Flask / Gunicorn', 'service_name': 'gestao_projetos.service', 'source': 'VPS Detected'},
            {'name': 'Unity Eleitoral', 'domain': 'eleitoral.unitytech.org.br', 'internal_port': 5007, 'path': '/var/www/unity_eleitoral', 'framework': 'Python Flask', 'service_name': 'unity_eleitoral.service', 'source': 'VPS Detected'},
            {'name': 'Instituto Unity', 'domain': 'unityinstituto.org.br', 'internal_port': 3001, 'path': '/var/www/site_unity', 'framework': 'Node.js / Express', 'service_name': 'pm2-root.service', 'source': 'VPS Detected'},
            {'name': 'JHenrique Team', 'domain': 'jhenriqueteam.com.br', 'internal_port': 5001, 'path': '/var/www/projeto_personal', 'framework': 'Node.js / React', 'service_name': 'pm2-root.service', 'source': 'VPS Detected'},
            {'name': 'Unity Tech Web', 'domain': 'unitytech.org.br', 'internal_port': 80, 'path': '/var/www/meu_react', 'framework': 'React Static', 'service_name': 'nginx.service', 'source': 'VPS Detected'}
        ]

        # Merge unique by domain
        domains_seen = {d['domain'] for d in discovered}
        for item in real_known:
            if item['domain'] not in domains_seen:
                discovered.append(item)

        return discovered
    except Exception as e:
        return []
