import os
import re
from modules.ssh_manager import execute_command

def detect_app_database(server_data, app_data):
    """
    Scans the application directory on the VPS for database connection traces in:
    - .env files
    - requirements.txt / package.json
    - Python configuration files (app.py, config.py, settings.py)
    Returns detected database type ('postgresql', 'mysql', 'sqlite') and host/port without exposing credentials.
    """
    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')

    target_path = app_data['path']

    cmd = f"""python3 - << 'EOF'
import os, sys, re, json

app_path = "{target_path}"
db_type = 'none'
db_host = 'localhost'
db_port = 5432
db_name = None

if os.path.exists(app_path):
    for root, dirs, files in os.walk(app_path):
        if 'venv' in root or '.venv' in root or 'node_modules' in root:
            continue
        for fname in files:
            if fname.endswith(('.env', '.py', '.js', '.json', '.txt', '.yml', '.yaml')):
                fpath = os.path.join(root, fname)
                try:
                    with open(fpath, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()

                    if 'postgresql' in content or 'psycopg2' in content or 'pg_dump' in content or '5432' in content:
                        db_type = 'postgresql'
                        db_port = 5432
                    elif 'mysql' in content or 'pymysql' in content or '3306' in content:
                        db_type = 'mysql'
                        db_port = 3306
                    elif 'sqlite' in content:
                        db_type = 'sqlite'

                    match_name = re.search(r'(?:DATABASE_URL|SQLALCHEMY_DATABASE_URI|DB_NAME)\s*[:=]\s*[\'"]?([a-zA-Z0-9_\-\/]+)', content)
                    if match_name:
                        val = match_name.group(1)
                        if '/' in val:
                            db_name = val.split('/')[-1]
                        else:
                            db_name = val
                except Exception:
                    pass

print(json.dumps({{
    'db_type': db_type,
    'host': db_host,
    'port': db_port,
    'name': db_name or (os.path.basename(app_path) + '_db')
}}))
EOF
"""
    exit_code, out, _ = execute_command(srv, cmd)
    if exit_code == 0 and out.strip():
        try:
            return json.loads(out.strip())
        except Exception:
            pass
    return {'db_type': 'none', 'host': 'localhost', 'port': 5432, 'name': None}
