import os
import socket
import subprocess

def scan():
    """
    Scan the system and return a profile dict.
    Used by ai.py to generate context-aware honeyfiles.
    """
    profile = {}

    # Hostname
    profile['hostname'] = socket.gethostname()

    # OS info
    try:
        with open('/etc/os-release') as f:
            lines = f.read()
        for line in lines.splitlines():
            if line.startswith('PRETTY_NAME'):
                profile['os'] = line.split('=')[1].strip('"')
                break
    except:
        profile['os'] = 'Linux'

    # Installed software
    software = []
    checks = [
        'apache2', 'nginx', 'mysql', 'postgresql', 'mongodb',
        'docker', 'php', 'python3', 'nodejs', 'wordpress',
        'ssh', 'ftp', 'samba', 'redis', 'elasticsearch'
    ]
    for pkg in checks:
        try:
            result = subprocess.run(
                ['which', pkg],
                capture_output=True, text=True
            )
            if result.returncode == 0:
                software.append(pkg)
        except:
            pass
    profile['software'] = software

    # Running services
    services = []
    try:
        result = subprocess.run(
            ['systemctl', 'list-units', '--type=service',
             '--state=running', '--no-pager', '--no-legend'],
            capture_output=True, text=True
        )
        for line in result.stdout.splitlines():
            parts = line.strip().split()
            if parts:
                services.append(parts[0].replace('.service', ''))
    except:
        pass
    profile['services'] = services[:10]

    # Folders in /home
    home_folders = []
    try:
        for user in os.listdir('/home'):
            user_path = f'/home/{user}'
            if os.path.isdir(user_path):
                home_folders += os.listdir(user_path)
    except:
        pass
    profile['home_folders'] = list(set(home_folders))[:20]

    # Interesting folders on system
    interesting = []
    check_paths = [
        '/var/www', '/opt', '/srv', '/etc/nginx',
        '/etc/apache2', '/var/lib/mysql', '/root'
    ]
    for path in check_paths:
        if os.path.exists(path):
            interesting.append(path)
    profile['system_folders'] = interesting

    # Users on system
    users = []
    try:
        with open('/etc/passwd') as f:
            for line in f:
                parts = line.split(':')
                if len(parts) >= 7 and '/home/' in parts[5]:
                    users.append(parts[0])
    except:
        pass
    profile['users'] = users

    # File extensions found in home dirs
    extensions = set()
    try:
        for user in os.listdir('/home'):
            user_path = f'/home/{user}'
            if os.path.isdir(user_path):
                for fname in os.listdir(user_path):
                    ext = os.path.splitext(fname)[1]
                    if ext:
                        extensions.add(ext)
    except:
        pass
    profile['extensions'] = list(extensions)[:15]

    # Guess system type
    profile['system_type'] = guess_type(profile)

    return profile

def guess_type(profile):
    sw  = profile.get('software', [])
    fld = profile.get('home_folders', [])
    sfld = profile.get('system_folders', [])

    if any(x in sw for x in ['mysql', 'postgresql', 'mongodb']):
        if '/var/www' in sfld or 'nginx' in sw or 'apache2' in sw:
            return 'web_server'
        return 'database_server'
    if 'docker' in sw:
        return 'devops'
    if any(x in fld for x in ['accounting', 'finance', 'payroll', 'hr']):
        return 'office_finance'
    if '/var/www' in sfld or 'apache2' in sw or 'nginx' in sw:
        return 'web_server'
    return 'general'

if __name__ == "__main__":
    import json
    result = scan()
    print(json.dumps(result, indent=2))
