<?php
if (!defined('ABSPATH')) exit;

/**
 * Check la présence d'Ansible, Docker et Git via ton handler SSH
 */
function wpkginst_get_automation_readiness( $force = false ) {
    if ( ! $force ) {
        $cached = get_transient( 'wpkginst_readiness' );
        if ( $cached !== false ) {
            return $cached;
        }
    }

    $mapping = wpkginst_get_os_commands_mapping();
    $sudo    = ( get_option( 'wpkginst_ssh_username' ) === 'root' ) ? '' : 'sudo ';

    $result = [
        'ansible' => wpkginst_check_system_tool(
            'ansible-playbook --version',
            "{$sudo}{$mapping['update']} && {$sudo}{$mapping['install']} ansible"
        ),
        'docker_compose' => wpkginst_check_system_tool(
            'docker compose version',
            "{$sudo}{$mapping['update']} && {$sudo}{$mapping['install']} docker-compose-plugin"
        ),
        'git' => wpkginst_check_system_tool(
            'git --version',
            "{$sudo}{$mapping['install']} git"
        ),
    ];

    set_transient( 'wpkginst_readiness', $result, 2 * MINUTE_IN_SECONDS );

    return $result;
}

function wpkginst_check_system_tool($cmd, $install_cmd) {
    $res = wpkginst_execute_ssh_command($cmd);

    // Audit : On vérifie le succès de l'exécution et l'absence de messages d'erreur types
    $output = strtolower($res['output']);
    $is_installed = $res['success'] && !empty($res['output']) && 
                    strpos($output, 'not found') === false && 
                    strpos($output, 'no such') === false;

    return [
        'installed'   => $is_installed,
        'version'     => $is_installed ? trim(explode("\n", $res['output'])[0]) : null,
        'install_cmd' => $install_cmd
    ];
}

/**
 * Retourne le mapping des commandes par famille d'OS avec détection unique.
 */
function wpkginst_get_os_commands_mapping() {
    $family = get_transient('wpkginst_os_family');

    if (!$family) {
        $res = wpkginst_execute_ssh_command('cat /etc/os-release | grep "^ID=" | cut -d= -f2 | tr -d \'"\'');
        $id = ($res['success']) ? trim(strtolower($res['output'])) : 'debian';

        // Mapping étendu
        if (preg_match('/(debian|ubuntu|raspbian|kali|linuxmint|pop)/', $id)) {
            $family = 'debian';
        } elseif (preg_match('/(centos|fedora|rhel|almalinux|rocky|ol|amzn)/', $id)) {
            // "ol" = Oracle, "amzn" = Amazon Linux
            $family = 'redhat';
        } elseif (strpos($id, 'alpine') !== false) {
            $family = 'alpine';
        } elseif (preg_match('/(arch|manjaro)/', $id)) {
            $family = 'arch';
        } elseif (preg_match('/(suse|opensuse)/', $id)) {
            $family = 'suse';
        } else {
            $family = 'debian';
        }

        set_transient('wpkginst_os_family', $family, DAY_IN_SECONDS);
    }

    return wpkginst_get_hardcoded_mappings($family);
}

function wpkginst_get_hardcoded_mappings($family) {
    $all = [
        'debian' => [ // Debian, Ubuntu, Kali, Mint, Raspbian, Pop!_OS
            'update'  => 'apt-get update',
            'install' => 'apt-get install -y',
            'remove'  => 'apt-get purge -y',
            'check'   => "dpkg-query -W -f='\${Status}' %s 2>&1",
            'ready'   => 'install ok installed'
        ],
        'redhat' => [ // RHEL, CentOS, Fedora, AlmaLinux, Rocky Linux, Oracle Linux
            'update'  => 'dnf check-update', // dnf remplace yum sur les versions modernes
            'install' => 'dnf install -y',
            'remove'  => 'dnf remove -y',
            'check'   => 'rpm -q %s',
            'ready'   => 'is installed'
        ],
        'alpine' => [ // Alpine (Docker images)
            'update'  => 'apk update',
            'install' => 'apk add',
            'remove'  => 'apk del',
            'check'   => 'apk info -e %s',
            'ready'   => '%s'
        ],
        'arch' => [ // Arch Linux, Manjaro
            'update'  => 'pacman -Sy',
            'install' => 'pacman -S --noconfirm',
            'remove'  => 'pacman -Rs --noconfirm',
            'check'   => 'pacman -Qi %s',
            'ready'   => 'Name'
        ],
        'suse' => [ // openSUSE, SLE
            'update'  => 'zypper refresh',
            'install' => 'zypper install -y',
            'remove'  => 'zypper remove -y',
            'check'   => 'zypper info %s',
            'ready'   => 'Installed: Yes'
        ]
    ];

    return $all[$family] ?? $all['debian'];
}

/**
 * Audit : Cette fonction faisait doublon. 
 * On la simplifie pour qu'elle utilise le transient déjà détecté.
 */
function wpkginst_identify_os_family() {
    return get_transient('wpkginst_os_family') ?: 'debian';
}
