// puzzle_state.c
#include "puzzle_state.h"
#include <string.h>

void puzzle_state_init(puzzle_state_t *s) { memset(s, 0, sizeof(*s)); }

void puzzle_state_report(puzzle_state_t *s, uint8_t id,
                         const uint8_t *fragment, uint8_t len)
{
    if (id == 0 || id > PUZZLE_MAX_ID) return;
    if (len > PUZZLE_MAX_FRAG) len = PUZZLE_MAX_FRAG;
    if (s->solved[id]) return;                 // idempotent
    s->solved[id] = true;
    s->frag_len[id] = len;
    memcpy(s->frag[id], fragment, len);
}

int puzzle_state_code(const puzzle_state_t *s, char *out, size_t cap)
{
    if (cap == 0) return 0;
    int n = 0;
    for (uint8_t id = 1; id <= PUZZLE_MAX_ID; id++) {
        if (!s->solved[id]) continue;
        for (uint8_t k = 0; k < s->frag_len[id] && (size_t)(n + 1) < cap; k++)
            out[n++] = (char)('0' + (s->frag[id][k] % 10));
    }
    if ((size_t)n < cap) out[n] = '\0';
    return n;
}
