from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class MemoryRegion:
    name: str
    start: int
    end: int
    kind: str
    manual: str

    def contains(self, address: int) -> bool:
        return self.start <= address <= self.end


# Manual references:
# - H8/536 address map: Manual/0900766b802125d0.md:26503-26505
# - Vector/DTC low address area: Manual/0900766b802125d0.md:2944-2946
# - Register field H'FE80-H'FFFF: Manual/0900766b802125d0.md:2961-2968
# - On-chip RAM H'F680-H'FE7F: Manual/0900766b802125d0.md:17884-17894
MEMORY_REGIONS: tuple[MemoryRegion, ...] = (
    MemoryRegion("exception_vectors", 0x0000, 0x009F, "vectors", "section 2 address space"),
    MemoryRegion("dtc_vectors", 0x00A0, 0x00FF, "dtc_vectors", "section 2 address space"),
    MemoryRegion("program_or_external", 0x0100, 0xF67F, "program", "section 2/17 mode-dependent ROM or external space"),
    MemoryRegion("on_chip_ram", 0xF680, 0xFE7F, "ram", "section 16 RAM"),
    MemoryRegion("register_field", 0xFE80, 0xFFFF, "registers", "appendix B register map"),
)


def region_for(address: int) -> MemoryRegion:
    for region in MEMORY_REGIONS:
        if region.contains(address):
            return region
    return MemoryRegion("external_or_unmapped", address, address, "external", "outside page-0 on-chip ranges")
