import unittest

from h8536.emulator import H8536Emulator, ON_CHIP_RAM_START
from h8536.emulator.constants import (
    FRT_TCR_OCIEA,
    FRT_TCSR_CCLRA,
    FRT_TCSR_OCFA,
    FRT2_FRC_H,
    FRT2_OCRA_H,
    FRT1_TCR,
    FRT1_TCSR,
    FRT2_TCR,
    FRT2_TCSR,
    IPRC,
    VECTOR_FRT1_OCIA,
    VECTOR_FRT2_OCIA,
)
from h8536.emulator.timers import frt_internal_prescaler, frt_ocia_period_cycles


def rom_with_reset(*, reset: int = 0x1000, size: int = 0x1040) -> bytearray:
    rom = bytearray([0xFF] * size)
    rom[0:2] = reset.to_bytes(2, "big")
    return rom


def write_mov_b_abs_imm(rom: bytearray, address: int, target: int, value: int) -> int:
    rom[address : address + 5] = bytes([0x15, (target >> 8) & 0xFF, target & 0xFF, 0x06, value & 0xFF])
    return address + 5


class Frt2OciaTimerTest(unittest.TestCase):
    def test_manual_prescaler_bits_are_used_for_frt_timing(self):
        self.assertEqual(frt_internal_prescaler(0x00), 4)
        self.assertEqual(frt_internal_prescaler(0x01), 8)
        self.assertEqual(frt_internal_prescaler(0x02), 32)
        self.assertIsNone(frt_internal_prescaler(0x03))

    def test_rom_frt2_compare_period_is_100_ms_at_10_mhz(self):
        emulator = H8536Emulator(bytes(rom_with_reset()))
        emulator.memory.set_register8(FRT2_TCR, 0x02)
        emulator.memory.set_register16(FRT2_OCRA_H, 0x7A12)

        self.assertEqual(frt_ocia_period_cycles(0x02, 0x7A12), 1_000_000)
        self.assertEqual(emulator.frt2_ocia.period_ms(emulator.memory, 10_000_000), 100.0)

    def test_calibrated_scheduler_advances_frc_and_sets_ocfa(self):
        emulator = H8536Emulator(bytes(rom_with_reset()))
        emulator.memory.set_register8(FRT2_TCR, 0x02)
        emulator.memory.set_register8(FRT2_TCSR, FRT_TCSR_CCLRA)
        emulator.memory.set_register16(FRT2_FRC_H, 0x0000)
        emulator.memory.set_register16(FRT2_OCRA_H, 0x0003)

        emulator.frt2_ocia.tick(emulator.memory, 64)
        self.assertEqual(emulator.memory.register16(FRT2_FRC_H), 0x0002)
        self.assertEqual(emulator.memory.register8(FRT2_TCSR) & FRT_TCSR_OCFA, 0)

        emulator.frt2_ocia.tick(emulator.memory, 32)
        self.assertEqual(emulator.memory.register16(FRT2_FRC_H), 0x0000)
        self.assertEqual(emulator.memory.register8(FRT2_TCSR) & FRT_TCSR_OCFA, FRT_TCSR_OCFA)
        self.assertEqual(emulator.frt2_ocia.compare_matches, 1)

    def test_frt1_ocia_vector_can_fire_and_decrement_ram(self):
        rom = rom_with_reset()
        rom[VECTOR_FRT1_OCIA : VECTOR_FRT1_OCIA + 2] = (0x1020).to_bytes(2, "big")

        pc = 0x1000
        rom[pc : pc + 3] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        pc += 3
        # IPRC bits 6..4 are FRT1 and bits 2..0 are FRT2, so H'60 makes
        # only the FRT1 priority field high enough to pass interrupt mask 0.
        pc = write_mov_b_abs_imm(rom, pc, IPRC, 0x60)
        pc = write_mov_b_abs_imm(rom, pc, FRT1_TCR, FRT_TCR_OCIEA)
        rom[pc : pc + 2] = b"\x20\xFE"  # BRA self

        isr = 0x1020
        rom[isr : isr + 4] = bytes([0x15, (ON_CHIP_RAM_START >> 8) & 0xFF, ON_CHIP_RAM_START & 0xFF, 0x0C])
        isr += 4
        rom[isr : isr + 4] = bytes([0x15, (FRT1_TCSR >> 8) & 0xFF, FRT1_TCSR & 0xFF, 0xD5])
        rom[isr + 4] = 0x0A  # RTE

        emulator = H8536Emulator(bytes(rom), frt1_ocia_steps=2)
        emulator.memory.write8(ON_CHIP_RAM_START, 3)
        emulator.run(max_steps=5)

        self.assertEqual(emulator.memory.read8(ON_CHIP_RAM_START), 2)
        self.assertFalse(emulator.memory.read8(FRT1_TCSR) & FRT_TCSR_OCFA)
        self.assertEqual(emulator.cpu.pc, isr + 4)

    def test_frt1_ocia_does_not_fire_when_ociea_disabled(self):
        rom = rom_with_reset()
        rom[VECTOR_FRT1_OCIA : VECTOR_FRT1_OCIA + 2] = (0x1020).to_bytes(2, "big")

        pc = 0x1000
        rom[pc : pc + 3] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        pc += 3
        pc = write_mov_b_abs_imm(rom, pc, IPRC, 0x60)
        rom[pc : pc + 2] = b"\x20\xFE"  # BRA self

        rom[0x1020 : 0x1024] = bytes(
            [0x15, (ON_CHIP_RAM_START >> 8) & 0xFF, ON_CHIP_RAM_START & 0xFF, 0x0C]
        )
        rom[0x1024] = 0x0A  # RTE

        emulator = H8536Emulator(bytes(rom), frt1_ocia_steps=1)
        emulator.memory.write8(ON_CHIP_RAM_START, 3)
        emulator.run(max_steps=8)

        self.assertEqual(emulator.memory.read8(ON_CHIP_RAM_START), 3)
        self.assertEqual(emulator.memory.read8(FRT1_TCSR) & FRT_TCSR_OCFA, 0)
        self.assertEqual(emulator.cpu.pc, pc)

    def test_frt2_ocia_vector_can_fire_and_decrement_ram(self):
        rom = rom_with_reset()
        rom[VECTOR_FRT2_OCIA : VECTOR_FRT2_OCIA + 2] = (0x1020).to_bytes(2, "big")

        pc = 0x1000
        rom[pc : pc + 3] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        pc += 3
        # IPRC bits 6..4 are FRT1 and bits 2..0 are FRT2, so H'06 makes
        # only the FRT2 priority field high enough to pass interrupt mask 0.
        pc = write_mov_b_abs_imm(rom, pc, IPRC, 0x06)
        pc = write_mov_b_abs_imm(rom, pc, FRT2_TCR, FRT_TCR_OCIEA)
        rom[pc : pc + 2] = b"\x20\xFE"  # BRA self

        isr = 0x1020
        rom[isr : isr + 4] = bytes([0x15, (ON_CHIP_RAM_START >> 8) & 0xFF, ON_CHIP_RAM_START & 0xFF, 0x0C])
        isr += 4
        rom[isr : isr + 4] = bytes([0x15, (FRT2_TCSR >> 8) & 0xFF, FRT2_TCSR & 0xFF, 0xD5])
        rom[isr + 4] = 0x0A  # RTE

        emulator = H8536Emulator(bytes(rom), frt2_ocia_steps=2)
        emulator.memory.write8(ON_CHIP_RAM_START, 3)
        emulator.run(max_steps=5)

        self.assertEqual(emulator.memory.read8(ON_CHIP_RAM_START), 2)
        self.assertFalse(emulator.memory.read8(FRT2_TCSR) & FRT_TCSR_OCFA)
        self.assertEqual(emulator.cpu.pc, isr + 4)

    def test_calibrated_frt2_ocia_vector_can_fire_without_step_override(self):
        rom = rom_with_reset()
        rom[VECTOR_FRT2_OCIA : VECTOR_FRT2_OCIA + 2] = (0x1020).to_bytes(2, "big")

        pc = 0x1000
        rom[pc : pc + 3] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        pc += 3
        pc = write_mov_b_abs_imm(rom, pc, IPRC, 0x06)
        pc = write_mov_b_abs_imm(rom, pc, FRT2_TCR, FRT_TCR_OCIEA)
        rom[pc : pc + 2] = b"\x20\xFE"  # BRA self

        isr = 0x1020
        rom[isr : isr + 4] = bytes([0x15, (ON_CHIP_RAM_START >> 8) & 0xFF, ON_CHIP_RAM_START & 0xFF, 0x0C])
        isr += 4
        rom[isr : isr + 4] = bytes([0x15, (FRT2_TCSR >> 8) & 0xFF, FRT2_TCSR & 0xFF, 0xD5])
        rom[isr + 4] = 0x0A  # RTE

        emulator = H8536Emulator(bytes(rom))
        emulator.memory.write8(ON_CHIP_RAM_START, 3)
        emulator.memory.set_register8(FRT2_TCSR, FRT_TCSR_CCLRA)
        emulator.memory.set_register16(FRT2_FRC_H, 0x0000)
        emulator.memory.set_register16(FRT2_OCRA_H, 0x000A)
        emulator.run(max_steps=9)

        self.assertEqual(emulator.memory.read8(ON_CHIP_RAM_START), 2)
        self.assertFalse(emulator.memory.read8(FRT2_TCSR) & FRT_TCSR_OCFA)

    def test_frt2_ocia_does_not_fire_when_ociea_disabled(self):
        rom = rom_with_reset()
        rom[VECTOR_FRT2_OCIA : VECTOR_FRT2_OCIA + 2] = (0x1020).to_bytes(2, "big")

        pc = 0x1000
        rom[pc : pc + 3] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        pc += 3
        pc = write_mov_b_abs_imm(rom, pc, IPRC, 0x06)
        rom[pc : pc + 2] = b"\x20\xFE"  # BRA self

        rom[0x1020 : 0x1024] = bytes(
            [0x15, (ON_CHIP_RAM_START >> 8) & 0xFF, ON_CHIP_RAM_START & 0xFF, 0x0C]
        )
        rom[0x1024] = 0x0A  # RTE

        emulator = H8536Emulator(bytes(rom), frt2_ocia_steps=1)
        emulator.memory.write8(ON_CHIP_RAM_START, 3)
        emulator.run(max_steps=8)

        self.assertEqual(emulator.memory.read8(ON_CHIP_RAM_START), 3)
        self.assertEqual(emulator.memory.read8(FRT2_TCSR) & FRT_TCSR_OCFA, 0)
        self.assertEqual(emulator.cpu.pc, pc)


if __name__ == "__main__":
    unittest.main()
