/*
 * MSAC Trace - Export MSAC symbol decoding data for hardware verification
 * Output format: JSONL with one entry per decoded symbol
 */

#ifndef AOM_COMMON_MSAC_TRACE_H_
#define AOM_COMMON_MSAC_TRACE_H_

#include <stdio.h>
#include <stdint.h>
#include "aom_dsp/prob.h"

#ifdef __cplusplus
extern "C" {
#endif

#define MSAC_TRACE_MAX_CDF 16

typedef struct MsacTraceCtx {
    FILE *fp;
    char *output_dir;
    int enabled;
    int frame_num;
    int tile_row;
    int tile_col;
    int symbol_count;
    // Current block position for context
    int sb_row;
    int sb_col;
    int mi_row;
    int mi_col;
} MsacTraceCtx;

// Global context
MsacTraceCtx *msac_trace_get_global_ctx(void);

// Lifecycle
void msac_trace_init(MsacTraceCtx *ctx, const char *output_dir);
void msac_trace_close(MsacTraceCtx *ctx);

// Per-frame/tile control
void msac_trace_start_frame(MsacTraceCtx *ctx, int frame_num);
void msac_trace_end_frame(MsacTraceCtx *ctx);
void msac_trace_start_tile(MsacTraceCtx *ctx, int tile_row, int tile_col);
void msac_trace_end_tile(MsacTraceCtx *ctx);

// Position tracking
void msac_trace_set_sb(MsacTraceCtx *ctx, int sb_row, int sb_col);
void msac_trace_set_mi(MsacTraceCtx *ctx, int mi_row, int mi_col);

// Symbol tracing - call BEFORE decoding
// peek32: top 32 bits of window (dif)
// rng: current range
// cdf: CDF array (NULL for binary symbols)
// nsymbs: number of symbols in alphabet
void msac_trace_before_symbol(MsacTraceCtx *ctx,
                               const char *name,
                               uint32_t peek32,
                               uint16_t rng,
                               int16_t cnt,
                               const uint16_t *cdf,
                               int nsymbs);

// Symbol tracing - call AFTER decoding
// value: decoded symbol value
// new_rng: range after decoding
// shift: normalization shift applied
void msac_trace_after_symbol(MsacTraceCtx *ctx,
                              int value,
                              uint16_t new_rng,
                              int shift);

// Combined trace call (simpler interface)
void msac_trace_symbol(MsacTraceCtx *ctx,
                        const char *name,
                        uint32_t peek32_before,
                        uint16_t rng_before,
                        int16_t cnt,
                        const uint16_t *cdf,
                        int nsymbs,
                        int value,
                        uint16_t rng_after,
                        int shift);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AOM_COMMON_MSAC_TRACE_H_
