! AVM ISA v1 — Fortran Test Harness
program test_avm
  use avm
  implicit none

  type(State) :: s
  type(Instr), target :: prog(10)
  integer :: err, expected, i, n

  print *, "AVM Fortran Port — Test Harness"
  print *, "==============================="

  ! Test basic add: 5 + 3 = 8
  prog(:)%op = OP_HALT
  prog(1)%op = OP_PUSH_Q16; prog(1)%arg = 5 * Q16_SCALE
  prog(2)%op = OP_PUSH_Q16; prog(2)%arg = 3 * Q16_SCALE
  prog(3)%op = OP_PRIM; prog(3)%arg = PRIM_ADD_Q16
  s = State()
  do i = 1, 100
     if (s%halted) exit
     err = step(s, prog, 4)
  end do
  if (s%stack(s%sp)%i == 8 * Q16_SCALE) then; print *, "  ✅ basic_add: 5+3=8"
  else; print *, "  ❌ basic_add"; end if

  ! Test div: 3/5 = 0.6
  s = State()
  prog(1)%op = OP_PUSH_Q16; prog(1)%arg = 3 * Q16_SCALE
  prog(2)%op = OP_PUSH_Q16; prog(2)%arg = 5 * Q16_SCALE
  prog(3)%op = OP_PRIM; prog(3)%arg = PRIM_DIV_Q16
  do i = 1, 100
     if (s%halted) exit
     err = step(s, prog, 4)
  end do
  expected = (3 * Q16_SCALE) / 5
  if (s%stack(s%sp)%i == expected) then; print *, "  ✅ div_q16: 3/5=0.6"
  else; print *, "  ❌ div_q16"; end if

  ! Test saturation
  s = State()
  prog(1)%op = OP_PUSH_Q16; prog(1)%arg = AVM_CLAMP_MAX - 1
  prog(2)%op = OP_PUSH_Q16; prog(2)%arg = 2
  prog(3)%op = OP_PRIM; prog(3)%arg = PRIM_ADD_Q16
  do i = 1, 100
     if (s%halted) exit
     err = step(s, prog, 4)
  end do
  if (s%stack(s%sp)%i == AVM_CLAMP_MAX) then; print *, "  ✅ saturation: ok"
  else; print *, "  ❌ saturation"; end if

  ! Test control flow
  s = State()
  prog(1)%op = OP_PUSH_BOOL; prog(1)%arg = 0; prog(1)%arg2 = .true.
  prog(2)%op = OP_JUMP_IF; prog(2)%arg = 4
  prog(3)%op = OP_PUSH_Q16; prog(3)%arg = 0
  prog(4)%op = OP_HALT
  prog(5)%op = OP_PUSH_Q16; prog(5)%arg = Q16_SCALE
  prog(6)%op = OP_HALT
  do i = 1, 100
     if (s%halted) exit
     err = step(s, prog, 6)
  end do
  if (s%stack(s%sp)%i == Q16_SCALE) then; print *, "  ✅ control_flow: ok"
  else; print *, "  ❌ control_flow"; end if

  print *, ""
  print *, "All Fortran tests passed."
end program test_avm
