<?php

/**
 * Climate Controller Firmware API - Info/Status Endpoint
 *
 * URL Format: /api/v1/info
 *
 * Provides overall system status and available devices/stages.
 *
 * Response Format:
 * {
 *   "api_version": "1.0",
 *   "system_status": "operational",
 *   "supported_devices": [...],
 *   "supported_stages": [...],
 *   "device_status": {
 *     "rm-e32-r6-b6": {
 *       "dev": {"latest_version": "v1.2.3", "firmware_count": 5},
 *       "prod": {"latest_version": "v1.2.0", "firmware_count": 3}
 *     }
 *   },
 *   "total_firmware_files": 25,
 *   "disk_usage": "1.2GB",
 *   "last_updated": "2025-01-15T10:30:00Z"
 * }
 */

require_once 'common.php';

// Log the access
logAccess('system', 'info', 'system_info');

// Get system information using multi-product structure
$productStatus = [];
$totalFirmwareFiles = 0;
$lastUpdated = 0;
$allDevices = [];

foreach (VALID_PRODUCTS as $productId => $productConfig) {
    $productStatus[$productId] = [
        'name' => $productConfig['name'],
        'devices' => []
    ];

    foreach ($productConfig['devices'] as $device) {
        $allDevices[] = $device; // Collect all devices for supported_devices
        $productStatus[$productId]['devices'][$device] = [];

        foreach (VALID_STAGES as $stage) {
            $firmware = getFirmwareFiles($productId, $stage, $device);
            $count = count($firmware);
            $totalFirmwareFiles += $count;

            $stageInfo = [
                'firmware_count' => $count,
                'latest_version' => null,
                'last_updated' => null
            ];

            if (!empty($firmware)) {
                $latest = $firmware[0]; // First is newest
                $stageInfo['latest_version'] = $latest['version'] ?? 'unknown';
                $stageInfo['last_updated'] = date('c', $latest['modified']);
                $lastUpdated = max($lastUpdated, $latest['modified']);
            }

            $productStatus[$productId]['devices'][$device][$stage] = $stageInfo;
        }
    }
}

// Calculate disk usage (approximate)
$diskUsage = 0;
$firmwareBasePath = FIRMWARE_BASE_PATH;
if (is_dir($firmwareBasePath)) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($firmwareBasePath));
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'bin') {
            $diskUsage += $file->getSize();
        }
    }
}

// Format disk usage
function formatBytes($bytes, $precision = 1)
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }

    return round($bytes, $precision) . ' ' . $units[$i];
}

// Build response
$response = [
    'api_version' => '1.0',
    'system_status' => 'operational',
    'timestamp' => time(),
    'timestamp_iso' => date('c'),
    'supported_products' => array_keys(VALID_PRODUCTS),
    'supported_devices' => array_unique($allDevices),
    'supported_stages' => VALID_STAGES,
    'product_status' => $productStatus,
    'total_firmware_files' => $totalFirmwareFiles,
    'disk_usage' => formatBytes($diskUsage),
    'disk_usage_bytes' => $diskUsage,
    'last_updated' => $lastUpdated ? date('c', $lastUpdated) : null,
    'endpoints' => [
        'version' => '/api/v1/{product}/{stage}/{device}/version',
        'list' => '/api/v1/{product}/{stage}/{device}/list',
        'info' => '/api/v1/info',
        'products' => '/api/v1/products'
    ]
];

sendJsonResponse($response);
