<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

/**
 * 系统更新包归档格式识别（zip / tar.gz）。
 */
final class HostSystemUpdatePackageArchiveFormat
{
    public const ZIP = 'zip';

    public const TAR_GZ = 'tar.gz';

    public static function detectFromFile(string $path): string
    {
        if (! is_file($path)) {
            return self::ZIP;
        }

        $handle = @fopen($path, 'rb');

        if ($handle === false) {
            return self::extensionHint($path);
        }

        $header = fread($handle, 4) ?: '';
        fclose($handle);

        if (str_starts_with($header, "\x1F\x8B\x08")) {
            return self::TAR_GZ;
        }

        if (str_starts_with($header, 'PK')) {
            return self::ZIP;
        }

        return self::extensionHint($path);
    }

    public static function isSupported(string $format): bool
    {
        return in_array($format, [self::ZIP, self::TAR_GZ], true);
    }

    private static function extensionHint(string $path): string
    {
        $lower = strtolower(str_replace('\\', '/', $path));

        if (str_ends_with($lower, '.tar.gz') || str_ends_with($lower, '.tgz')) {
            return self::TAR_GZ;
        }

        return self::ZIP;
    }
}
