<?php
/**
 * container_stats.php — live per-container memory stats from cgroup v2, plus the
 * DB assembly that maps running site containers to their owner/domain/limit.
 *
 * Extracted from pages/dashboard.php so the same code backs both the initial
 * server-render and the dashboard's AJAX auto-reload endpoint
 * (api/dashboard-container-stats.php).
 */

if (!function_exists('get_container_memory_stats')) {
    /**
     * Read cgroup v2 memory.current + memory.stat for each named docker
     * container. $container_names is keyed by container name => ['limit_mb'=>,
     * 'site_name'=>, ...]. Returns per-container anon/cache/total/limit (MB).
     */
    function get_container_memory_stats($container_names) {
        $stats = [];
        foreach ($container_names as $name => $info) {
            $cid = trim(shell_exec("docker inspect " . escapeshellarg($name) . " --format '{{.Id}}' 2>/dev/null"));
            if (empty($cid)) continue;

            $cgroup_base = "/sys/fs/cgroup/system.slice/docker-{$cid}.scope";
            $current_file = "{$cgroup_base}/memory.current";
            $stat_file = "{$cgroup_base}/memory.stat";

            if (!file_exists($current_file) || !file_exists($stat_file)) continue;

            $total = intval(file_get_contents($current_file));
            $stat_content = file_get_contents($stat_file);

            $anon = 0;
            $file_cache = 0;
            if (preg_match('/^anon (\d+)/m', $stat_content, $m)) $anon = intval($m[1]);
            if (preg_match('/^file (\d+)/m', $stat_content, $m)) $file_cache = intval($m[1]);

            $stats[$name] = [
                'total_mb' => round($total / 1024 / 1024),
                'anon_mb' => round($anon / 1024 / 1024),
                'cache_mb' => round($file_cache / 1024 / 1024),
                'limit_mb' => $info['limit_mb'] ?? 0,
                'site_name' => $info['site_name'] ?? $name,
            ];
        }
        return $stats;
    }
}

if (!function_exists('whp_live_container_stats')) {
    /**
     * Build the live container memory table data: query running site containers
     * (optionally scoped to one owner), read their cgroup stats, and merge the
     * owner/domain back in. $scope_username = null (or 'root') = all containers;
     * otherwise only that user's. Returns the per-container stats array keyed by
     * container name, each with anon_mb/cache_mb/total_mb/limit_mb + username +
     * domain.
     */
    function whp_live_container_stats($db, $scope_username = null) {
        if (!$db) return [];

        $sql = "SELECT sc.container_number, s.site_name, s.memory_per_container, s.username,
                       COALESCE(sd.fqdn, d.domain_name) AS primary_domain
                FROM whp.site_containers sc
                JOIN whp.sites s ON sc.site_id = s.id
                JOIN whp.domains d ON s.primary_domain_id = d.id
                LEFT JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                WHERE sc.status = 'running'";
        $params = [];
        if ($scope_username !== null && $scope_username !== 'root') {
            $sql .= " AND s.username = ?";
            $params[] = $scope_username;
        }
        $sql .= " ORDER BY s.username, primary_domain, sc.container_number";

        $stmt = $db->prepare($sql);
        $stmt->execute($params);

        $containers_for_stats = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $safe_domain = str_replace('*.', 'wildcard.', $row['primary_domain']);
            $cname = $safe_domain . '-' . str_pad($row['container_number'], 2, '0', STR_PAD_LEFT);
            $containers_for_stats[$cname] = [
                'limit_mb' => intval($row['memory_per_container']),
                'site_name' => $row['site_name'],
                'username' => $row['username'],
                'domain' => $row['primary_domain'],
            ];
        }

        $stats = get_container_memory_stats($containers_for_stats);
        foreach ($stats as $cname => &$stat) {
            if (isset($containers_for_stats[$cname])) {
                $stat['username'] = $containers_for_stats[$cname]['username'];
                $stat['domain'] = $containers_for_stats[$cname]['domain'];
            }
        }
        unset($stat);
        return $stats;
    }
}
