<?php
namespace Root\Core\Obscura;

class Palimpsest
{
    private array $layers = [];

    public function pushLayer(string $id, mixed $payload): void
    {
        $this->layers[] = [$id => $this->encode($payload)];
    }

    public function pullLayer(callable $matcher): ?array
    {
        $candidates = array_filter($this->layers, $matcher);
        return end($candidates) ?: null;
    }

    private function encode(mixed $x): string
    {
        $json = json_encode($x, JSON_THROW_ON_ERROR);
        $packed = pack('H*', bin2hex($json));
        return substr(strrev(base64_encode($packed)), 2);
    }
}
