"""Draw an IsoDelve map (isodelve-map@1) from its JSON and the public art pack.

    pip install pillow
    python draw_map.py map.json out.png --angle iso0 --scale 0.25 --walls cutaway

Pack files are public, so no API key is needed here. Get map.json from your own
server (POST /v1/maps with your key) and keep the key out of client code.
"""
import argparse, io, json, math, urllib.request
from functools import cmp_to_key
from PIL import Image

FACINGS = ["iso0", "iso90", "iso180", "iso270"]
SIGN = {"iso0": (1, 1), "iso90": (1, -1), "iso180": (-1, -1), "iso270": (-1, 1)}  # signs of sin, cos of the view bearing
T = 0.1                                              # half wall thickness, in cells
LIFT = (3.048 + 0.2) * math.cos(math.radians(30)) * 256 / (1.524 * math.sqrt(2))  # tallest piece, in px at scale 1
UA = {"User-Agent": "isodelve-guide-example"}

def get(url):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA)) as r:
        return r.read()

def project(f, gx, gy):
    """Grid point (gx east, gy south, in cells) -> screen px at scale 1."""
    s, c = SIGN[f]
    return 128 * (gx * c + gy * s), -64 * (gx * s - gy * c)

def depth(f, gx, gy):
    s, c = SIGN[f]
    return -(gx * s - gy * c)                         # bigger = nearer the camera

def sprite_facing(f, rot):
    return FACINGS[(FACINGS.index(f) - rot) % 4]

def apply_walls(m, f, mode):
    """walls=auto lowers wall segments standing in front of floor; cutaway lowers them all."""
    g = m["grid"]; W, H = g["w"], g["h"]; s, c = SIGN[f]; pal = g["palette"]
    floor_at = lambda x, y: 0 <= x < W and 0 <= y < H and g["floor"][y * W + x] != 0
    def low(pid, behind_is_floor):
        if not pid or not pid.startswith("wall.seg.full.") or mode == "full" or (mode == "auto" and not behind_is_floor):
            return pid
        return pid.replace("wall.seg.full.", "wall.seg.cut.")
    eh = [low(pal[v], floor_at(k % W, k // W - 1 if c > 0 else k // W)) for k, v in enumerate(g["edgeH"])]
    ev = [low(pal[v], floor_at(k % (W + 1) if s > 0 else k % (W + 1) - 1, k // (W + 1))) for k, v in enumerate(g["edgeV"])]
    full = lambda pid: bool(pid) and (pid.startswith("portal.") or ".full." in pid)
    vx = []
    for k, v in enumerate(g["vertex"]):
        pid = pal[v]; x, y = k % (W + 1), k // (W + 1)
        if pid:
            near = [ev[(y - 1) * (W + 1) + x] if y > 0 else "", ev[y * (W + 1) + x] if y < H else "",
                    eh[y * W + x] if x < W else "", eh[y * W + x - 1] if x > 0 else ""]
            if not any(full(n) for n in near):
                pid = pid[:-5] + ".cut" if pid.endswith(".full") else pid
        vx.append(pid)
    return eh, ev, vx

def draw_list(m, f, mode, footprints):
    g = m["grid"]; W, H = g["w"], g["h"]; pal = g["palette"]
    eh, ev, vx = apply_walls(m, f, mode)
    items = []
    def add(pid, rot, box, layer):
        if not pid: return
        gx, gy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
        px, py = project(f, gx, gy)
        items.append(dict(id=pid, facing=sprite_facing(f, rot), px=px, py=py, box=box, layer=layer, key=depth(f, gx, gy), order=len(items)))
    for y in range(H):
        for x in range(W):
            add(pal[g["floor"][y * W + x]], g["floorRot"][y * W + x], (x, y, x + 1, y + 1), 0)
    for y in range(H + 1):
        for x in range(W):
            add(eh[y * W + x], 0, (x + T, y - T, x + 1 - T, y + T), 1)
    for y in range(H):
        for x in range(W + 1):
            add(ev[y * (W + 1) + x], 1, (x - T, y + T, x + T, y + 1 - T), 1)
    for y in range(H + 1):
        for x in range(W + 1):
            add(vx[y * (W + 1) + x], g["vertexRot"][y * (W + 1) + x], (x - T, y - T, x + T, y + T), 1)
    for p in m["props"]:                              # at = north-west cell of the footprint; dims swap on odd rot
        w, d = footprints.get(p["piece"], (1, 1)); dx, dy = (d, w) if p["rot"] % 2 else (w, d); x, y = p["at"]
        add(p["piece"], p["rot"], (x + T, y + T, x + dx - T, y + dy - T), 1)
    cmp = lambda a, b: (a["key"] > b["key"]) - (a["key"] < b["key"]) or (a["px"] > b["px"]) - (a["px"] < b["px"]) or a["order"] - b["order"]
    floors = sorted([i for i in items if i["layer"] == 0], key=cmp_to_key(cmp))
    return floors + topo(f, [i for i in items if i["layer"] == 1], cmp)

def topo(f, items, cmp):
    """Standing pieces: draw each after every screen-overlapping piece wholly behind it on a grid axis."""
    s, c = SIGN[f]
    def behind(a, b):
        a, b = a["box"], b["box"]
        east = a[0] >= b[2] if s > 0 else a[2] <= b[0]
        south = a[3] <= b[1] if c > 0 else a[1] >= b[3]
        return east or south
    def rect(it):
        pts = [project(f, it["box"][i], it["box"][j]) for i in (0, 2) for j in (1, 3)]
        xs, ys = [p[0] for p in pts], [p[1] for p in pts]
        return min(xs), min(ys) - LIFT, max(xs), max(ys)
    R = [rect(i) for i in items]; n = len(items)
    succ = [[] for _ in items]; indeg = [0] * n
    by_x = sorted(range(n), key=lambda i: R[i][0])
    for u, i in enumerate(by_x):
        for j in by_x[u + 1:]:
            if R[j][0] >= R[i][2]: break
            if R[j][1] >= R[i][3] or R[i][1] >= R[j][3]: continue
            ij, ji = behind(items[i], items[j]), behind(items[j], items[i])
            if ij and not ji: succ[i].append(j); indeg[j] += 1
            elif ji and not ij: succ[j].append(i); indeg[i] += 1
    key = cmp_to_key(lambda a, b: cmp(items[a], items[b]))
    ready = sorted([i for i in range(n) if indeg[i] == 0], key=key); out = []; done = [False] * n
    while len(out) < n:
        if not ready:                                 # a cycle (never seen): release the shallowest remaining piece
            ready = [min((i for i in range(n) if not done[i]), key=key)]
        i = ready.pop(0)
        if done[i]: continue
        done[i] = True; out.append(items[i])
        for j in succ[i]:
            indeg[j] -= 1
            if indeg[j] == 0 and not done[j]:
                ready.append(j); ready.sort(key=key)
    return out

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("map"); ap.add_argument("out")
    ap.add_argument("--angle", default="iso0", choices=FACINGS)
    ap.add_argument("--scale", type=float, default=0.25, choices=[1, 0.5, 0.25])
    ap.add_argument("--walls", default="cutaway", choices=["full", "cutaway", "auto"])
    ap.add_argument("--api", default="https://api.isodelve.com")
    a = ap.parse_args()
    m = json.load(open(a.map))
    assert m["format"] == "isodelve-map@1", m["format"]
    pack_id, version = m["pack"].split("@")
    base = f"{a.api}/v1/packs/{pack_id}/{version}/"
    manifest = json.loads(get(base + "manifest.json"))
    footprints = {p["id"]: tuple(p.get("footprint", (1, 1))) for p in manifest["pieces"]}
    sprites = {}                                      # (piece, facing) -> cropped RGBA sprite + anchor
    for ref in manifest["atlases"]:
        if ref["scale"] != a.scale: continue
        data = json.loads(get(base + ref["data"]))
        sheet = Image.open(io.BytesIO(get(base + ref["image"]))).convert("RGBA")
        for fr in data["frames"]:
            sprites[(fr["id"], ref["facing"])] = (sheet.crop((fr["x"], fr["y"], fr["x"] + fr["w"], fr["y"] + fr["h"])), fr["ax"], fr["ay"])
    items = draw_list(m, a.angle, a.walls, footprints)
    # Canvas = bounds of every sprite frame placed at its anchor, plus 8 px padding.
    boxes = []
    for it in items:
        img, ax, ay = sprites[(it["id"], it["facing"])]
        left, top = it["px"] * a.scale - ax, it["py"] * a.scale - ay
        boxes.append((left, top, left + img.width, top + img.height))
    x0, y0 = min(b[0] for b in boxes), min(b[1] for b in boxes)
    x1, y1 = max(b[2] for b in boxes), max(b[3] for b in boxes)
    pad = 8; ox, oy = -x0 + pad, -y0 + pad
    out = Image.new("RGBA", (round(x1 - x0 + 2 * pad), round(y1 - y0 + 2 * pad)), (239, 230, 210, 255))  # parchment
    for it in items:
        img, ax, ay = sprites[(it["id"], it["facing"])]
        out.alpha_composite(img, (round(ox + it["px"] * a.scale - ax), round(oy + it["py"] * a.scale - ay)))
    out.save(a.out)
    print(f"{a.out}: {out.width}x{out.height}, {len(items)} sprites, {m['id']} {a.angle} scale {a.scale} walls {a.walls}")

if __name__ == "__main__":
    main()
