#!/usr/bin/env python3
"""从 Unity Level{N}.prefab 解析 Tilemap（Ground / Border）格子数据。"""
from __future__ import annotations

import re
from pathlib import Path


def parse_tilemap_layer(text: str, layer_name: str) -> dict[str, int]:
    parts = re.split(r"(?=--- !u!1 &)", text)
    for part in parts:
        if f"m_Name: {layer_name}" not in part or "Tilemap:" not in part:
            continue
        tiles: dict[str, int] = {}
        for m in re.finditer(
            r"first: \{x: (-?\d+), y: (-?\d+), z: 0\}[\s\S]*?m_TileIndex: (\d+)",
            part,
        ):
            x, y, ti = int(m.group(1)), int(m.group(2)), int(m.group(3))
            tiles[f"{x},{y}"] = ti
        return tiles
    return {}


def parse_level_prefab(prefab_path: Path) -> dict:
    if not prefab_path.is_file():
        return {}
    text = prefab_path.read_text(encoding="utf-8")
    g_raw = parse_tilemap_layer(text, "Ground")
    b_raw = parse_tilemap_layer(text, "Border")
    if not g_raw and not b_raw:
        return {}
    ground = {
        k: ("JumpBlock" if ti == 1 else "Baseblock") for k, ti in g_raw.items()
    }
    border = {k: True for k in b_raw}
    return {"ground": ground, "border": border}
