<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support\PluginRelease;

use RuntimeException;
use ZipArchive;

/**
 * 计算官方插件 ZIP 归档哈希（排除自描述 manifest.json，避免循环依赖）。
 */
class OfficialPluginReleaseArchiveHasher
{
    public const EXCLUDED_ENTRIES = [
        'manifest.json',
    ];

    public function computeSha256(string $zipPath, array $excludeEntries = self::EXCLUDED_ENTRIES): string
    {
        $zip = new ZipArchive;
        $opened = $zip->open($zipPath);

        if ($opened !== true) {
            throw new RuntimeException("Unable to open zip archive for hashing: {$zipPath}");
        }

        $entries = [];

        for ($index = 0; $index < $zip->numFiles; $index++) {
            $name = $zip->getNameIndex($index);

            if (! is_string($name) || $name === '' || str_ends_with($name, '/')) {
                continue;
            }

            if ($this->shouldExcludeEntry($name, $excludeEntries)) {
                continue;
            }

            $content = $zip->getFromIndex($index);

            if ($content === false) {
                $zip->close();
                throw new RuntimeException("Unable to read zip entry for hashing: {$name}");
            }

            $entries[$name] = $content;
        }

        $zip->close();
        ksort($entries, SORT_STRING);

        $context = hash_init('sha256');

        foreach ($entries as $name => $content) {
            hash_update($context, $name."\0".$content);
        }

        $hash = hash_final($context);

        return is_string($hash) && $hash !== '' ? strtolower($hash) : '';
    }

    /**
     * @param  list<string>  $excludeEntries
     */
    private function shouldExcludeEntry(string $name, array $excludeEntries): bool
    {
        $normalized = str_replace('\\', '/', ltrim($name, '/'));

        foreach ($excludeEntries as $excludeEntry) {
            if ($normalized === str_replace('\\', '/', ltrim($excludeEntry, '/'))) {
                return true;
            }
        }

        return false;
    }
}
