<?php

declare(strict_types=1);

namespace Kylin\Cadpa\Services;

/**
 * CADPA 适龄提示与版号合规自检服务
 *
 * 功能：
 * - 适龄等级（8+/12+/16+）查询
 * - 版号审核合规清单自检
 * - 标识展示规范校验
 */
final class CadpaService
{
    /**
     * 版号审核合规自检。
     *
     * @param  array<string, bool> $results  各自检项的通过状态 ['realname' => true, 'no_guest' => false, ...]
     * @return array{passed:bool, total:int, passed_count:int, failed:array, optional_missing:array}
     */
    public function audit(array $results): array
    {
        $checklist = config('kylin-cadpa.checklist', []);
        $failed = [];
        $optionalMissing = [];
        $passedCount = 0;

        foreach ($checklist as $item) {
            $code = $item['code'];
            $passed = $results[$code] ?? false;

            if ($passed) {
                $passedCount++;
                continue;
            }

            if ($item['required']) {
                $failed[] = [
                    'code' => $code,
                    'name' => $item['name'],
                ];
            } else {
                $optionalMissing[] = [
                    'code' => $code,
                    'name' => $item['name'],
                ];
            }
        }

        return [
            'passed'          => empty($failed),
            'total'           => count($checklist),
            'passed_count'    => $passedCount,
            'failed'          => $failed,
            'optional_missing'=> $optionalMissing,
        ];
    }

    /**
     * 根据年龄获取适龄等级。
     *
     * @return array{label:string, min_age:int, name:string}|null
     */
    public function ratingForAge(int $age): ?array
    {
        $ratings = config('kylin-cadpa.age_ratings', []);

        // 从高到低匹配
        foreach (array_reverse(array_keys($ratings), true) as $minAge) {
            if ($age >= $minAge) {
                return $ratings[$minAge];
            }
        }

        return null;
    }

    /**
     * 根据游戏 CADPA 标识等级获取展示规范。
     *
     * @return array{min_size_ratio:float, video_min_seconds:int, click_to_expand:bool}
     */
    public function displaySpec(): array
    {
        return config('kylin-cadpa.display', [
            'min_size_ratio'    => 0.1,
            'video_min_seconds' => 3,
            'click_to_expand'   => true,
        ]);
    }
}
