<?php

namespace App\Services\Stack;

/**
 * The complete list of hosting stack components the AI Portal recognizes.
 * Each entry includes:
 *   - id:           stable key used in servers.stack JSON
 *   - name:         display label
 *   - category:     UI grouping
 *   - detect:       shell snippet (run as part of audit) — non-empty stdout
 *                   means installed. Optional version_regex extracts version.
 *   - restart:      command to restart this component (used by chat templates)
 *   - mutually_exclusive: hint to the UI for radio-style picking within group
 *
 * Adding a new component = add an entry here. Detector + chat templates
 * pick it up automatically.
 */
class StackRegistry
{
    public const COMPONENTS = [
        // ============== CONTROL PANEL ==============
        'cpanel' => [
            'name' => 'cPanel/WHM', 'category' => 'panel', 'mutually_exclusive' => true,
            'detect' => '[ -x /usr/local/cpanel/cpanel ] && /usr/local/cpanel/cpanel -V 2>/dev/null',
            'version_regex' => '/^([\d.]+)/',
            'restart' => '/scripts/restartsrv_cpsrvd',
        ],
        'webuzo' => [
            'name' => 'Webuzo', 'category' => 'panel', 'mutually_exclusive' => true,
            'detect' => '[ -d /usr/local/webuzo ] && cat /usr/local/webuzo/version 2>/dev/null',
        ],
        'directadmin' => [
            'name' => 'DirectAdmin', 'category' => 'panel', 'mutually_exclusive' => true,
            'detect' => '[ -d /usr/local/directadmin ] && /usr/local/directadmin/directadmin v 2>/dev/null',
            'restart' => 'service directadmin restart',
        ],
        'plesk' => [
            'name' => 'Plesk', 'category' => 'panel', 'mutually_exclusive' => true,
            'detect' => '[ -d /opt/psa ] && /opt/psa/version 2>/dev/null',
        ],
        'cyberpanel' => [
            'name' => 'CyberPanel', 'category' => 'panel', 'mutually_exclusive' => true,
            'detect' => '[ -d /usr/local/CyberCP ] && cat /usr/local/CyberCP/version.py 2>/dev/null',
        ],

        // ============== WEB SERVER ==============
        'apache' => [
            'name' => 'Apache (httpd)', 'category' => 'web',
            'detect' => 'systemctl is-active httpd 2>/dev/null || systemctl is-active apache2 2>/dev/null',
            'restart' => '/scripts/restartsrv_httpd 2>/dev/null || systemctl restart httpd 2>/dev/null || systemctl restart apache2',
        ],
        'litespeed' => [
            'name' => 'LiteSpeed', 'category' => 'web',
            'detect' => 'systemctl is-active lsws 2>/dev/null || systemctl is-active lshttpd 2>/dev/null || [ -d /usr/local/lsws ] && echo present',
            'restart' => 'systemctl restart lsws 2>/dev/null || /usr/local/lsws/bin/lswsctrl restart',
        ],
        'openlitespeed' => [
            'name' => 'OpenLiteSpeed', 'category' => 'web',
            'detect' => '[ -d /usr/local/lsws ] && [ ! -f /usr/local/lsws/conf/serial.no ] && echo present',
        ],
        'nginx' => [
            'name' => 'nginx', 'category' => 'web',
            'detect' => 'systemctl is-active nginx 2>/dev/null',
            'restart' => 'systemctl restart nginx',
        ],

        // ============== PHP ==============
        'php_fpm' => [
            'name' => 'PHP-FPM', 'category' => 'php',
            'detect' => 'systemctl is-active php-fpm 2>/dev/null || systemctl list-units --no-legend "php*-fpm*" 2>/dev/null | head -1',
            'restart' => 'systemctl restart php-fpm',
        ],
        'lsapi' => [
            'name' => 'LSAPI (LiteSpeed PHP)', 'category' => 'php',
            'detect' => '[ -d /usr/local/lsws/lsphp* ] && echo present',
        ],

        // ============== DATABASE ==============
        'mariadb' => [
            'name' => 'MariaDB', 'category' => 'db',
            'detect' => 'systemctl is-active mariadb 2>/dev/null || mariadb --version 2>/dev/null',
            'version_regex' => '/Distrib\s+([\d.]+)/',
            'restart' => 'systemctl restart mariadb',
        ],
        'mysql' => [
            'name' => 'MySQL', 'category' => 'db',
            'detect' => 'systemctl is-active mysqld 2>/dev/null || systemctl is-active mysql 2>/dev/null',
            'restart' => 'systemctl restart mysqld 2>/dev/null || systemctl restart mysql',
        ],
        'postgresql' => [
            'name' => 'PostgreSQL', 'category' => 'db',
            'detect' => 'systemctl is-active postgresql 2>/dev/null',
            'restart' => 'systemctl restart postgresql',
        ],

        // ============== CACHE ==============
        'redis' => [
            'name' => 'Redis', 'category' => 'cache',
            'detect' => 'systemctl is-active redis 2>/dev/null || systemctl is-active redis-server 2>/dev/null',
            'restart' => 'systemctl restart redis 2>/dev/null || systemctl restart redis-server',
        ],
        'memcached' => [
            'name' => 'Memcached', 'category' => 'cache',
            'detect' => 'systemctl is-active memcached 2>/dev/null',
            'restart' => 'systemctl restart memcached',
        ],

        // ============== MAIL ==============
        'exim' => [
            'name' => 'Exim', 'category' => 'mail',
            'detect' => 'systemctl is-active exim 2>/dev/null || command -v exim 2>/dev/null',
            'restart' => '/scripts/restartsrv_exim 2>/dev/null || systemctl restart exim',
        ],
        'postfix' => [
            'name' => 'Postfix', 'category' => 'mail',
            'detect' => 'systemctl is-active postfix 2>/dev/null',
            'restart' => 'systemctl restart postfix',
        ],
        'dovecot' => [
            'name' => 'Dovecot', 'category' => 'mail',
            'detect' => 'systemctl is-active dovecot 2>/dev/null',
            'restart' => '/scripts/restartsrv_dovecot 2>/dev/null || systemctl restart dovecot',
        ],
        'spamassassin' => [
            'name' => 'SpamAssassin', 'category' => 'mail',
            'detect' => 'systemctl is-active spamd 2>/dev/null || systemctl is-active spamassassin 2>/dev/null',
        ],
        'opendkim' => [
            'name' => 'OpenDKIM', 'category' => 'mail',
            'detect' => 'systemctl is-active opendkim 2>/dev/null',
        ],

        // ============== BACKUP ==============
        'jetbackup' => [
            'name' => 'JetBackup', 'category' => 'backup',
            'detect' => '[ -x /usr/local/jetapps/usr/bin/jetbackup ] && /usr/local/jetapps/usr/bin/jetbackup --version 2>/dev/null',
        ],
        'backuply' => [
            'name' => 'Backuply', 'category' => 'backup',
            'detect' => '[ -d /usr/local/cpanel/3rdparty/backuply ] && echo present',
        ],
        'acronis' => [
            'name' => 'Acronis Backup', 'category' => 'backup',
            'detect' => 'systemctl is-active acronis_mms 2>/dev/null || [ -d /opt/acronis ] && echo present',
        ],
        'r1soft' => [
            'name' => 'R1Soft', 'category' => 'backup',
            'detect' => '[ -x /usr/sbin/serverbackup-setup ] && echo present',
        ],
        'cpanel_backup' => [
            'name' => 'cPanel Backups', 'category' => 'backup',
            'detect' => '[ -f /var/cpanel/backups/config ] && echo present',
        ],

        // ============== SECURITY ==============
        'cloudlinux' => [
            'name' => 'CloudLinux', 'category' => 'security',
            'detect' => '[ -x /usr/sbin/cldetect ] && cldetect --check-license 2>/dev/null',
        ],
        'cagefs' => [
            'name' => 'CageFS', 'category' => 'security',
            'detect' => '[ -x /usr/sbin/cagefsctl ] && cagefsctl --list-enabled 2>/dev/null | head -1',
        ],
        'lve' => [
            'name' => 'LVE Manager', 'category' => 'security',
            'detect' => 'lsmod 2>/dev/null | grep ^lve | head -1',
        ],
        'imunify360' => [
            'name' => 'Imunify360', 'category' => 'security',
            'detect' => '[ -x /usr/bin/imunify360-agent ] && imunify360-agent version 2>/dev/null',
            'restart' => 'systemctl restart imunify360',
        ],
        'imunifyav' => [
            'name' => 'ImunifyAV', 'category' => 'security',
            'detect' => '[ -x /usr/bin/imunify-antivirus ] && echo present',
        ],
        'cpguard' => [
            'name' => 'CPGuard', 'category' => 'security',
            'detect' => '[ -d /opt/cpguard ] && echo present',
        ],
        'csf' => [
            'name' => 'CSF (ConfigServer Firewall)', 'category' => 'security',
            'detect' => '[ -x /usr/sbin/csf ] && csf -v 2>/dev/null | head -1',
            'version_regex' => '/v([\d.]+)/',
        ],
        'lfd' => [
            'name' => 'LFD (Login Failure Daemon)', 'category' => 'security',
            'detect' => 'systemctl is-active lfd 2>/dev/null',
        ],
        'fail2ban' => [
            'name' => 'fail2ban', 'category' => 'security',
            'detect' => 'systemctl is-active fail2ban 2>/dev/null',
            'restart' => 'systemctl restart fail2ban',
        ],
        'maldet' => [
            'name' => 'Linux Malware Detect', 'category' => 'security',
            'detect' => '[ -x /usr/local/sbin/maldet ] && echo present',
        ],
        'clamav' => [
            'name' => 'ClamAV', 'category' => 'security',
            'detect' => 'systemctl is-active clamd@scan 2>/dev/null || command -v clamscan 2>/dev/null',
        ],

        // ============== MONITORING ==============
        'hsagent' => [
            'name' => 'HostSeba Agent', 'category' => 'monitoring',
            'detect' => 'id hsagent 2>/dev/null',
        ],
        'noc_agent' => [
            'name' => 'NOC Agent', 'category' => 'monitoring',
            'detect' => 'systemctl is-active hostseba-noc-agent 2>/dev/null',
        ],
        'datadog' => [
            'name' => 'Datadog Agent', 'category' => 'monitoring',
            'detect' => 'systemctl is-active datadog-agent 2>/dev/null',
        ],
        'newrelic' => [
            'name' => 'New Relic', 'category' => 'monitoring',
            'detect' => 'systemctl is-active newrelic-infra 2>/dev/null || systemctl is-active newrelic-daemon 2>/dev/null',
        ],

        // ============== MISC ==============
        'docker' => [
            'name' => 'Docker', 'category' => 'misc',
            'detect' => 'systemctl is-active docker 2>/dev/null',
            'restart' => 'systemctl restart docker',
        ],
        'kernelcare' => [
            'name' => 'KernelCare', 'category' => 'misc',
            'detect' => '[ -x /usr/bin/kcarectl ] && kcarectl --info 2>/dev/null | head -1',
        ],
    ];

    public const CATEGORIES = [
        'panel'      => 'Control Panel',
        'web'        => 'Web Server',
        'php'        => 'PHP',
        'db'         => 'Database',
        'cache'      => 'Cache',
        'mail'       => 'Mail Stack',
        'backup'     => 'Backup',
        'security'   => 'Security',
        'monitoring' => 'Monitoring',
        'misc'       => 'Other',
    ];

    /**
     * Components grouped by category — used by the UI picker.
     */
    public static function grouped(): array
    {
        $groups = array_fill_keys(array_keys(self::CATEGORIES), []);
        foreach (self::COMPONENTS as $id => $meta) {
            $groups[$meta['category']][] = ['id' => $id] + $meta;
        }
        return $groups;
    }

    public static function get(string $id): ?array
    {
        return self::COMPONENTS[$id] ?? null;
    }

    /**
     * Composite "what this server is" tag for use in chat prompt context.
     * E.g. "cPanel + LiteSpeed + MariaDB + Imunify360".
     */
    public static function summary(array $stack): string
    {
        $parts = [];
        foreach ($stack as $id => $entry) {
            if (! ($entry['installed'] ?? false)) continue;
            $parts[] = self::COMPONENTS[$id]['name'] ?? $id;
        }
        return $parts ? implode(' · ', $parts) : '(stack not yet detected)';
    }
}
