///|
/// GBA Keypad button bit indices (active-low in KEYINPUT `0x04000130`).
pub const KEY_A : Int32 = 0

///|
pub const KEY_B : Int32 = 1

///|
pub const KEY_SELECT : Int32 = 2

///|
pub const KEY_START : Int32 = 3

///|
pub const KEY_RIGHT : Int32 = 4

///|
pub const KEY_LEFT : Int32 = 5

///|
pub const KEY_UP : Int32 = 6

///|
pub const KEY_DOWN : Int32 = 7

///|
pub const KEY_R : Int32 = 8

///|
pub const KEY_L : Int32 = 9

///|
/// Top-level Game Boy Advance console combining ARM7TDMI CPU, 32-bit Bus, DMA, Timers, HLE BIOS, and PPU.
pub struct Gba {
  cpu : Cpu
  bus : GbaBus
}

///|
/// Construct a new GBA instance loaded with the given ROM image bytes.
pub fn Gba::new(rom : Bytes) -> Gba {
  { cpu: Cpu::new(), bus: GbaBus::new(rom), }
}

///|
/// Reset CPU, RAM, I/O registers, DMA, timers, and PPU while keeping the loaded ROM.
pub fn Gba::reset(self : Gba) -> Unit {
  self.cpu.reset()
  self.bus.reset()
}

///|
/// Load a new ROM image and reset the console.
pub fn Gba::load_rom(self : Gba, rom : Bytes) -> Unit {
  self.bus.rom = rom
  self.reset()
}

///|
/// Set the pressed state of a GBA keypad button (`KEY_A`..`KEY_L`).
pub fn Gba::set_key(self : Gba, key : Int32, pressed : Bool) -> Unit {
  if key < 0 || key > 9 {
    return
  }
  let bit = 1U << key
  if pressed {
    self.bus.keyinput = self.bus.keyinput & bit.lnot()
  } else {
    self.bus.keyinput = self.bus.keyinput | bit
  }
}

///|
/// Set debug PPU layer visibility mask (`bit0=BG0..bit3=BG3, bit4=OBJ`).
pub fn Gba::set_layer_mask(self : Gba, mask : UInt32) -> Unit {
  self.bus.ppu.layer_mask = mask & 0x1FU
}

///|
/// Execute one CPU instruction, tick timers and PPU, and dispatch pending IRQs.
/// Returns cycles consumed.
pub fn Gba::step(self : Gba) -> Int32 {
  // Dispatch pending IRQ if enabled
  let pending = self.bus.irq_ie & self.bus.irq_if
  if pending != 0U {
    if self.bus.irq_ime != 0U {
      let _ = self.cpu.trigger_irq()
    } else {
      self.cpu.halted = false
    }
  }
  let cycles = if self.cpu.halted {
    // Fast-forward halted CPU up to next scanline boundary
    let rem = if !self.bus.ppu.in_hblank {
      CYCLES_HDRAW - self.bus.ppu.line_cycles
    } else {
      CYCLES_SCANLINE - self.bus.ppu.line_cycles
    }
    let step_c = if rem > 0 { rem } else { 1 }
    self.cpu.cycles += step_c.to_uint64()
    step_c
  } else {
    self.cpu.step(self.bus)
  }
  tick_timers(self.bus, cycles)
  let _ = tick_ppu(self.bus, cycles)
  cycles
}

///|
/// Run the GBA until one complete video frame (280,896 cycles) has been rendered.
pub fn Gba::step_frame(self : Gba) -> Unit {
  let target = self.bus.ppu.frame_count + 1UL
  while self.bus.ppu.frame_count < target {
    let _ = self.step()
  }
}

///|
/// Run the GBA for `frames` complete video frames.
pub fn Gba::run_frames(self : Gba, frames : Int32) -> Unit {
  for _i = 0; _i < frames; _i = _i + 1 {
    self.step_frame()
  }
}

///|
/// Return the 240x160 RGBA8888 framebuffer (`240 * 160 * 4` bytes).
pub fn Gba::framebuffer(self : Gba) -> FixedArray[Byte] {
  self.bus.ppu.framebuf
}

///|
/// Export the current 240x160 framebuffer as a binary PPM (P6) image.
pub fn Gba::framebuffer_ppm(self : Gba) -> Bytes {
  let buf = @buffer.Buffer(size_hint=SCREEN_WIDTH * SCREEN_HEIGHT * 3 + 32)
  let header = "P6\n240 160\n255\n"
  for ch in header {
    buf.write_byte((ch.to_int() & 0xFF).to_byte())
  }
  let fb = self.bus.ppu.framebuf
  for i = 0; i < SCREEN_WIDTH * SCREEN_HEIGHT; i = i + 1 {
    buf.write_byte(fb[i * 4])
    buf.write_byte(fb[i * 4 + 1])
    buf.write_byte(fb[i * 4 + 2])
  }
  buf.to_bytes()
}

///|
/// Read the 12-byte ASCII game title from the GBA ROM header (`0x080000A0..0x080000AB`).
pub fn Gba::rom_title(self : Gba) -> String {
  let sb = StringBuilder()
  for i = 0; i < 12; i = i + 1 {
    let off = 0xA0 + i
    if off < self.bus.rom.length() {
      let c = self.bus.rom[off].to_int()
      if c >= 32 && c < 127 {
        sb.write_char(c.unsafe_to_char())
      }
    }
  }
  sb.to_string()
}

///|
/// Disassemble `count` instructions starting from current PC (respecting ARM/Thumb mode).
pub fn Gba::disassemble_around_pc(self : Gba, count : Int32) -> Array[String] {
  let out : Array[String] = []
  let thumb = self.cpu.is_thumb()
  let step : UInt32 = if thumb { 2U } else { 4U }
  let pc0 = self.cpu.pc()
  for i = 0; i < count; i = i + 1 {
    let addr = pc0 + i.reinterpret_as_uint() * step
    let line = if thumb {
      let op = self.bus.read16(addr)
      "0x\{hex32(addr)}: \{hex16(op)}  \{disassemble_thumb(op, addr)}"
    } else {
      let op = self.bus.read32(addr)
      "0x\{hex32(addr)}: \{hex32(op)}  \{disassemble_arm(op, addr)}"
    }
    out.push(line)
  }
  out
}

///|
/// Render the current BG/OBJ Palette RAM (512 colors) as a standalone SVG palette swatch sheet.
pub fn Gba::render_palette_svg(self : Gba) -> String {
  let sb = StringBuilder()
  sb.write_string(
    "",
  )
  sb.write_string(
    "",
  )
  sb.write_string(
    "BG Palette (0..255)",
  )
  for row = 0; row < 16; row = row + 1 {
    for col = 0; col < 16; col = col + 1 {
      let idx = row * 16 + col
      let c = read_pram16(self.bus.pram, idx)
      let (r, g, b) = bgr555_to_rgb(c)
      let x = 4 + col * 16
      let y = 20 + row * 8
      sb.write_string(
        "",
      )
    }
  }
  sb.write_string(
    "OBJ Palette (256..511)",
  )
  for row = 0; row < 16; row = row + 1 {
    for col = 0; col < 16; col = col + 1 {
      let idx = 256 + row * 16 + col
      let c = read_pram16(self.bus.pram, idx)
      let (r, g, b) = bgr555_to_rgb(c)
      let x = 4 + col * 16
      let y = 166 + row * 8
      sb.write_string(
        "",
      )
    }
  }
  sb.write_string("")
  sb.to_string()
}

///|
/// Summary of RGB channel averages and exact color counts in the current framebuffer.
pub fn Gba::framebuffer_stats(self : Gba) -> (Int32, Int32, Int32, Int32) {
  let fb = self.bus.ppu.framebuf
  let mut sum_r = 0
  let mut sum_g = 0
  let mut sum_b = 0
  let mut non_black = 0
  let n = SCREEN_WIDTH * SCREEN_HEIGHT
  for i = 0; i < n; i = i + 1 {
    let r = fb[i * 4].to_int()
    let g = fb[i * 4 + 1].to_int()
    let b = fb[i * 4 + 2].to_int()
    sum_r += r
    sum_g += g
    sum_b += b
    if r != 0 || g != 0 || b != 0 {
      non_black += 1
    }
  }
  (sum_r / n, sum_g / n, sum_b / n, non_black)
}