<?php
declare(strict_types=1);
require __DIR__.'/peer_sync_lib.php';
require_peer_auth($config);
$action = strtolower(trim((string)($_GET['action'] ?? 'status')));
[$dir,$file,$lockFile,$hist] = storage_paths($config);
try {
    if ($action === 'status') {
        method('GET'); $s=read_state($file);
        respond(['exists'=>(int)$s['revision']>0&&is_array($s['payload']),'revision'=>(int)$s['revision'],'checksum'=>$s['checksum'],'updated_at'=>$s['updated_at'],'device_id'=>$s['device_id'],'peer_id'=>$config['peer_id']??null]);
    }
    if ($action === 'pull') {
        method('GET'); $s=read_state($file);
        if ((int)$s['revision']===0 || !is_array($s['payload'])) respond(['error'=>'El servidor todavía no contiene una copia SIAPA.'],404);
        respond(['revision'=>(int)$s['revision'],'checksum'=>$s['checksum'],'updated_at'=>$s['updated_at'],'payload'=>$s['payload']]);
    }
    if ($action === 'push') {
        method('POST'); $in=input_json((int)$config['max_payload_bytes']);
        $state=peer_store_payload($config,peer_validate_payload($in['payload']??null),substr(trim((string)($in['device_id']??'PEER')),0,160),max(0,(int)($in['base_revision']??0)));
        respond(['ok'=>true,'revision'=>(int)$state['revision'],'checksum'=>$state['checksum'],'updated_at'=>$state['updated_at']]);
    }
    respond(['error'=>'Acción de réplica no válida.'],404);
} catch (SiapaPeerException $e) {
    respond(array_merge(['error'=>$e->getMessage()],$e->details),$e->httpStatus);
}
