<?php
require_once __DIR__ . '/../../_bootstrap.php';
require_once ROOT_PATH . '/includes/match_functions.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonResponse(['ok'=>false,'erro'=>'Método não permitido.'],405);
afValidarCsrfApi();
$u = afApiOuSessaoUsuario($pdo);
$d = requestJson();
$sessaoId = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['sessao_id'] ?? '')));
$safeToken = preg_replace('/[^a-f0-9]/', '', strtolower((string)($d['safe_token'] ?? '')));
if (strlen($sessaoId) !== 48) jsonResponse(['ok'=>false,'erro'=>'Sessão inválida.'],422);
try {
    $match=afBuscarPartidaPorSessao($pdo,(int)$u['id'],$sessaoId);if(!$match)throw new RuntimeException('Partida não encontrada.');
    $feature=!empty($match['controlled_event_id'])?'controlled_event_farm':'farm';
    afMinorPolicyApiAssert($pdo,$u,$feature,!empty($match['controlled_event_id'])?['controlled_event_id'=>(int)$match['controlled_event_id']]:[]);
    $safeCamera = afSafeCameraRecord($pdo,(int)$u['id'],$sessaoId,$safeToken,$d);
    $p = afRegistrarMovimento($pdo,(int)$u['id'],(int)$u['dispositivo_id'],$sessaoId,!empty($safeCamera['scoring_allowed'])?(float)($d['intensidade']??0):0.0,(int)($d['sequencia']??0),(int)($d['tempo']??0),[
        'modo'=>(string)($d['modo']??'movimento'),'pose_detectada'=>!empty($d['pose_detectada']),'confianca'=>(float)($d['confianca']??0),'cobertura'=>(float)($d['cobertura']??0),'precisao'=>(float)($d['precisao']??0),'fluidez'=>(float)($d['fluidez']??0),'originalidade'=>(float)($d['originalidade']??0),'dificuldade'=>(float)($d['dificuldade']??0),'maos'=>(int)($d['maos']??0),'frames_pose'=>(int)($d['frames_pose']??0),'frames_maos'=>(int)($d['frames_maos']??0),'movimento'=>(string)($d['movimento']??''),'liveness_nonce'=>(string)($d['liveness_nonce']??''),'liveness_passed'=>!empty($d['liveness_passed']),'safety_paused'=>empty($safeCamera['scoring_allowed']),'safety_reason'=>(string)($safeCamera['reason']??'none'),
    ]);
    if (($p['status'] ?? '') === 'finalizada') afSafeCameraClose($pdo,(int)$u['id'],$sessaoId,$safeToken,'finished');
    jsonResponse(['ok'=>true,'partida'=>afPartidaPublica($p,$pdo),'safe_camera'=>afSafeCameraApiState($safeCamera)]);
} catch (Throwable $e) { jsonResponse(['ok'=>false,'erro'=>$e->getMessage()],422); }
