/*
 * Copyright (c) 2016, Alliance for Open Media. All rights reserved.
 *
 * This source code is subject to the terms of the BSD 2 Clause License and
 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
 * was not distributed with this source code in the LICENSE file, you can
 * obtain it at www.aomedia.org/license/software. If the Alliance for Open
 * Media Patent License 1.0 was not distributed with this source code in the
 * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
 */

#include <assert.h> 
#include <stdint.h> 
#include <stdio.h> // For trace

#include "config/aom_config.h"

#include "aom_dsp/bitreader_buffer.h"
#include "aom_dsp/recenter.h"
#include "aom_ports/bitops.h"

// --- TRACE HELPER (JSONL per OBU) ---
static FILE* g_rb_trace_fp = NULL;
static int g_rb_obu_counter = 0;
static char g_rb_output_dir[256] = "trace_output";
static int g_rb_trace_enabled = 1;

void aom_rb_trace_set_output_dir(const char *dir) {
    if (dir) {
        strncpy(g_rb_output_dir, dir, sizeof(g_rb_output_dir) - 1);
        g_rb_output_dir[sizeof(g_rb_output_dir) - 1] = '\0';
    }
}

// Legacy function - now just increments counter for compatibility
void aom_rb_trace_start_frame(int frame_num) {
    (void)frame_num;
    // No-op - use aom_rb_trace_start_obu instead
}

void aom_rb_trace_end_frame(void) {
    // No-op - use aom_rb_trace_end_obu instead
}

// New per-OBU trace functions
void aom_rb_trace_start_obu(int obu_type, const char* type_name) {
    if (!g_rb_trace_enabled) return;

    // Close previous OBU file
    if (g_rb_trace_fp) {
        fclose(g_rb_trace_fp);
        g_rb_trace_fp = NULL;
    }

    // Open new OBU file
    char filename[512];
    snprintf(filename, sizeof(filename), "%s/obu_%04d_%s.jsonl",
             g_rb_output_dir, g_rb_obu_counter++, type_name);
    g_rb_trace_fp = fopen(filename, "w");
    if (!g_rb_trace_fp) {
        fprintf(stderr, "Warning: Could not open OBU trace file: %s\n", filename);
    }
}

void aom_rb_trace_end_obu(void) {
    if (g_rb_trace_fp) {
        fclose(g_rb_trace_fp);
        g_rb_trace_fp = NULL;
    }
}

void aom_rb_trace_reset_counter(void) {
    g_rb_obu_counter = 0;
}

// Peek next 32 bits without consuming
static uint32_t peek32(struct aom_read_bit_buffer *rb) {
    uint32_t value = 0;
    uint32_t pos = rb->bit_offset;
    size_t total_bits = (rb->bit_buffer_end - rb->bit_buffer) * 8;

    for (int i = 0; i < 32; i++) {
        if (pos >= total_bits) {
            value <<= 1;
        } else {
            size_t byte_idx = pos >> 3;
            int bit_idx = 7 - (pos & 7);
            value = (value << 1) | ((rb->bit_buffer[byte_idx] >> bit_idx) & 1);
        }
        pos++;
    }
    return value;
}

static void trace_rb_symbol(uint32_t peek, const char* name, uint32_t val, int bits) {
    if (!name) return; // Don't trace internal sub-reads
    if (!g_rb_trace_fp) return;

    fprintf(g_rb_trace_fp, "{\"peek32\":\"0x%08X\",\"name\":\"%s\",\"value\":%u,\"bits\":%d}\n", peek, name, val, bits);
}
// --------------------

size_t aom_rb_bytes_read(const struct aom_read_bit_buffer *rb) {
  return (rb->bit_offset + 7) >> 3;
}

int aom_rb_read_bit(struct aom_read_bit_buffer *rb, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  const uint32_t off = rb->bit_offset;
  const uint32_t p = off >> 3;
  const int q = 7 - (int)(off & 0x7);
  int bit = 0;

  if (rb->bit_buffer + p < rb->bit_buffer_end) {
    bit = (rb->bit_buffer[p] >> q) & 1;
    rb->bit_offset = off + 1;
  } else {
    if (rb->error_handler) rb->error_handler(rb->error_handler_data);
    bit = 0;
  }

  if (name) trace_rb_symbol(p32, name, bit, 1);
  return bit;
}

int aom_rb_read_literal(struct aom_read_bit_buffer *rb, int bits, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  assert(bits <= 31);
  int value = 0, bit;
  // Use NULL for name to suppress individual bit tracing
  for (bit = bits - 1; bit >= 0; bit--) value |= aom_rb_read_bit(rb, NULL) << bit;

  if (name) trace_rb_symbol(p32, name, value, bits);
  return value;
}

#if CONFIG_AV1_DECODER
uint32_t aom_rb_read_unsigned_literal(struct aom_read_bit_buffer *rb,
                                      int bits, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  assert(bits <= 32);
  uint32_t value = 0;
  int bit;
  for (bit = bits - 1; bit >= 0; bit--)
    value |= (uint32_t)aom_rb_read_bit(rb, NULL) << bit;

  if (name) trace_rb_symbol(p32, name, value, bits);
  return value;
}

int aom_rb_read_inv_signed_literal(struct aom_read_bit_buffer *rb, int bits, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  const int nbits = sizeof(unsigned) * 8 - bits - 1;
  const unsigned value = (unsigned)aom_rb_read_literal(rb, bits + 1, NULL) << nbits;
  int ret = ((int)value) >> nbits;

  if (name) trace_rb_symbol(p32, name, (uint32_t)ret, bits + 1);
  return ret;
}
#endif  // CONFIG_AV1_DECODER

uint32_t aom_rb_read_uvlc(struct aom_read_bit_buffer *rb, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  int leading_zeros = 0;
  while (leading_zeros < 32 && !aom_rb_read_bit(rb, NULL)) ++leading_zeros;
  // Maximum 32 bits.
  if (leading_zeros == 32) return UINT32_MAX;  // Error.
  const uint32_t base = (1u << leading_zeros) - 1;
  const uint32_t value = aom_rb_read_literal(rb, leading_zeros, NULL);
  uint32_t ret = base + value;

  if (name) trace_rb_symbol(p32, name, ret, -1); // -1 indicates variable length
  return ret;
}

#if CONFIG_AV1_DECODER
static uint16_t aom_rb_read_primitive_quniform(struct aom_read_bit_buffer *rb,
                                               uint16_t n) {
  if (n <= 1) return 0;
  const int l = get_msb(n) + 1;
  const int m = (1 << l) - n;
  const int v = aom_rb_read_literal(rb, l - 1, NULL);
  return v < m ? v : (v << 1) - m + aom_rb_read_bit(rb, NULL);
}

static uint16_t aom_rb_read_primitive_subexpfin(struct aom_read_bit_buffer *rb,
                                                uint16_t n, uint16_t k) {
  int i = 0;
  int mk = 0;

  while (1) {
    int b = (i ? k + i - 1 : k);
    int a = (1 << b);

    if (n <= mk + 3 * a) {
      return aom_rb_read_primitive_quniform(rb, n - mk) + mk;
    }

    if (!aom_rb_read_bit(rb, NULL)) {
      return aom_rb_read_literal(rb, b, NULL) + mk;
    }

    i = i + 1;
    mk += a;
  }

  assert(0);
  return 0;
}

static uint16_t aom_rb_read_primitive_refsubexpfin(
    struct aom_read_bit_buffer *rb, uint16_t n, uint16_t k, uint16_t ref) {
  return inv_recenter_finite_nonneg(n, ref,
                                    aom_rb_read_primitive_subexpfin(rb, n, k));
}

int16_t aom_rb_read_signed_primitive_refsubexpfin(
    struct aom_read_bit_buffer *rb, uint16_t n, uint16_t k, int16_t ref, const char* name) {
  uint32_t p32 = name ? peek32(rb) : 0;
  ref += n - 1;
  const uint16_t scaled_n = (n << 1) - 1;
  int16_t ret = aom_rb_read_primitive_refsubexpfin(rb, scaled_n, k, ref) - n + 1;

  if (name) trace_rb_symbol(p32, name, (uint32_t)ret, -2); // -2 complex encoding
  return ret;
}
#endif  // CONFIG_AV1_DECODER