<?php
declare(strict_types=1);
namespace App\Services\Trust;

final class TrustManifestValidator
{
    /** @return array{ok:bool,issues:list<string>,warnings:list<string>,metadata:array<string,mixed>} */
    public function validate(mixed $manifest): array
    {
        $issues=[];$warnings=[];$metadata=[];
        if(!is_array($manifest)) return ['ok'=>false,'issues'=>['manifest.json absent ou JSON invalide.'],'warnings'=>[],'metadata'=>[]];
        foreach(['package','package_id','version','min_version','signature_algorithm','files'] as $field){
            if(!array_key_exists($field,$manifest)||$manifest[$field]===''||$manifest[$field]===[]) $issues[]="Champ obligatoire absent : {$field}.";
        }
        if(isset($manifest['version'])&&!preg_match('/^\d+\.\d+\.\d+(?:[.-][0-9A-Za-z.-]+)?$/',(string)$manifest['version'])) $issues[]='Version du package invalide.';
        foreach(['min_version','max_version'] as $f){if(isset($manifest[$f])&&$manifest[$f]!==''&&!preg_match('/^\d+\.\d+\.\d+(?:[.-][0-9A-Za-z.-]+)?$/',(string)$manifest[$f]))$issues[]="{$f} invalide.";}
        if(($manifest['signature_algorithm']??'')!=='Ed25519') $issues[]='Algorithme de signature non autorisé : Ed25519 requis.';
        if(empty($manifest['publisher'])) $warnings[]='Éditeur non déclaré.';
        if(empty($manifest['build_number'])) $warnings[]='Numéro de build non déclaré.';
        if(empty($manifest['trust_level'])) $warnings[]='Niveau de confiance déclaré absent.';
        if(isset($manifest['package_uuid'])&&!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',(string)$manifest['package_uuid'])) $issues[]='package_uuid invalide.';
        $metadata=['package'=>(string)($manifest['package']??''),'package_id'=>(string)($manifest['package_id']??''),'version'=>(string)($manifest['version']??''),'publisher'=>(string)($manifest['publisher']??''),'trust_level'=>(string)($manifest['trust_level']??'')];
        return ['ok'=>empty($issues),'issues'=>$issues,'warnings'=>$warnings,'metadata'=>$metadata];
    }
}
