import json
from types import SimpleNamespace

terrain_map = {
    "0": " ",  # nothing
    "16": " ",  # perimeter
    "4": ".",
    "4194308": "v",  # stair_down
    "8388612": "^",  # stair_up
    "13107": "d",  # door
    "26214": "L",  # door, locked
    "52429": "T",  # door, trapped
    "10485": "S",  # door, secret
    "65540": "A",  # arch
    "20971": "H",  # portcullis
    "82208": "1",
    "83886": "2",
    "8556": "3",
    "87241": "4",
    "88919": "5",
    "90597": "6",
    "92274": "7",
    "93952": "8",
    "95630": "9",
    "80530": "0",
}


def get_char(key: str, default: str = None) -> str:
    return terrain_map.get(key) or terrain_map.get(key[:5]) or terrain_map.get(key[:4]) or default


def convert_donjon(source: str) -> str:
    src = SimpleNamespace(**json.loads(source))

    textmap = ""
    for y in range(1, len(src.cells) - 1):
        row = src.cells[y]
        for x in range(1, len(row) - 1):
            char = get_char(str(row[x]), default=".")
            if not char:
                raise Exception(f"{textmap}\nMissing value {row[x]} at ({y}, {x})")
            textmap += char
        textmap += "\n"
    return textmap.rstrip()
