import re
import json

with open("001 마인크래프트_조합법_대백과.md", "r", encoding="utf-8") as f:
    text = f.read()

categories = [
    {"id": "tools", "title": "도구 및 채굴", "code": "4.1"},
    {"id": "combat", "title": "전투 및 방어구", "code": "4.2"},
    {"id": "building", "title": "건축 블록", "code": "4.3"},
    {"id": "decoration", "title": "장식 및 주민 직업 블록", "code": "4.4"},
    {"id": "redstone", "title": "레드스톤 및 기계", "code": "4.5"},
    {"id": "transport", "title": "운송 수단", "code": "4.6"},
    {"id": "food", "title": "식료품 및 요리", "code": "4.7"},
    {"id": "utility", "title": "유틸리티 및 특수 기능", "code": "4.8"},
    {"id": "brewing", "title": "양조 및 마법", "code": "4.9"},
    {"id": "materials", "title": "재료, 원자재 압축/환원 & 염료", "code": "4.10"},
    {"id": "misc", "title": "기타 잡화", "code": "4.11"},
]

lines = text.split("\n")
recipes = []
current_cat = None

def parse_grid_str(grid_str):
    rows = grid_str.split("<br>")
    grid = []
    for r in rows:
        r = r.strip()
        slots = re.findall(r"\[(.*?)\]", r)
        row_slots = []
        for s in slots:
            clean_s = s.strip()
            row_slots.append(clean_s if clean_s else "")
        while len(row_slots) < 3:
            row_slots.append("")
        grid.append(row_slots[:3])
    while len(grid) < 3:
        grid.append(["", "", ""])
    return grid[:3]

in_dye_table = False

for line in lines:
    line_strip = line.strip()
    
    if line_strip.startswith("### 4."):
        in_dye_table = False
        for c in categories:
            if c["code"] in line_strip:
                current_cat = c
                break
    elif line_strip.startswith("#### 🎨 16색 공식 염료"):
        in_dye_table = True
        continue
    elif line_strip.startswith("---") or line_strip.startswith("## 5."):
        in_dye_table = False

    if not current_cat:
        continue

    # Regular 4-column recipe table
    if not in_dye_table and line_strip.startswith("| **") and not line_strip.startswith("| **구분**") and not line_strip.startswith("| **대분류"):
        cols = [c.strip() for c in line.split("|")[1:-1]]
        if len(cols) == 4:
            raw_name, raw_grid, raw_ingr, raw_desc = cols
            
            # Skip header lines
            if "완성 아이템" in raw_name:
                continue

            name_match = re.search(r"\*\*(.*?)\*\*", raw_name)
            name = name_match.group(1) if name_match else raw_name
            subname = ""
            sub_match = re.search(r"<br>\*\((.*?)\)\*", raw_name)
            if sub_match:
                subname = sub_match.group(1)
            
            count = 1
            count_match = re.search(r"\*\((\d+)개\)\*", raw_name)
            if count_match:
                count = int(count_match.group(1))
            
            is2x2 = "[🎒 2×2 가능]" in raw_desc or "[🎒 2×2 가능]" in raw_name or "2×2" in raw_desc
            is_shapeless = "무형 조합" in raw_desc
            
            grid = parse_grid_str(raw_grid)
            ing_lines = [ing.strip().replace("+ ", "") for ing in raw_ingr.split("<br>")]
            
            clean_id = re.sub(r"[^a-zA-Z0-9가-힣]", "_", name).strip("_").lower()
            if not clean_id:
                clean_id = f"item_{len(recipes)+1}"
            
            recipes.append({
                "id": clean_id,
                "name": name,
                "subname": subname,
                "category": current_cat["title"],
                "categoryId": current_cat["id"],
                "outputCount": count,
                "is2x2": is2x2,
                "recipeType": "무형 조합" if is_shapeless else "형태 조합",
                "grid": grid,
                "ingredientsRaw": raw_ingr.replace("<br>", " + "),
                "ingredientsList": ing_lines,
                "description": raw_desc
            })
    
    # 16 Dyes 3-column table
    elif in_dye_table and line_strip.startswith("| **"):
        cols = [c.strip() for c in line.split("|")[1:-1]]
        if len(cols) == 3:
            raw_name, raw_ingr, raw_source = cols
            if "완성 염료" in raw_name:
                continue
            name_match = re.search(r"\*\*(.*?)\*\*", raw_name)
            name = name_match.group(1) if name_match else raw_name
            dye_name = f"{name} 염료" if not name.endswith("염료") else name
            
            grid = [
                [raw_ingr.split(",")[0].split("또는")[0].strip(" `[]"), "", ""],
                ["", "", ""],
                ["", "", ""]
            ]
            recipes.append({
                "id": f"dye_{len(recipes)+1}",
                "name": dye_name,
                "subname": "16색 공식 염료",
                "category": "재료, 원자재 압축/환원 & 염료",
                "categoryId": "materials",
                "outputCount": 1,
                "is2x2": True,
                "recipeType": "무형 조합",
                "grid": grid,
                "ingredientsRaw": raw_ingr,
                "ingredientsList": [raw_ingr],
                "description": f"무형 조합 [🎒 2×2 가능]: {raw_ingr}. 수급처: {raw_source}"
            })

print(f"Total parsed recipes: {len(recipes)}")
print("Sample first:", recipes[0]["name"])
print("Sample last:", recipes[-1]["name"])
