from pathlib import Path
import re


RESOURCE = Path(r"C:\GDMO\BDMO\DProject_vs2022\Tool\MapTool\MapTool.rc")

# Only visible resource captions are changed. Resource IDs, positions, and styles remain intact.
TRANSLATIONS = {
    "라이트의\\nAmbient 값 사용": "Use Light\\nAmbient Value",
    "단축키로 사용할 키를 입력하여 주십시오.\\nShift, Ctrl, Alt 지원됩니다.": "Enter the key to use as a shortcut.\\nShift, Ctrl, and Alt are supported.",
    "마지막 작업 실행을 취소합니다.\\n실행 취소": "Undo the last action.\\nUndo",
    "이전에 실행 취소된 작업을 다시 실행합니다.\\n다시 실행": "Redo the previously undone action.\\nRedo",
    "도구 모음을 표시하거나 숨깁니다.\\n도구 모음 설정/해제": "Show or hide the toolbar.\\nToggle Toolbar",
    "문서를 저장할지를 묻고 응용 프로그램을 끝냅니다.\\n끝내기": "Ask whether to save the document and exit the application.\\nExit",
    "창이 겹치지 않도록 바둑판식으로 정렬합니다.\\n바둑판식 창 배열": "Tile windows so they do not overlap.\\nTile Windows",
    "창이 겹치도록 계단식으로 정렬합니다.\\n계단식 창 배열": "Arrange windows in a cascade.\\nCascade Windows",
    "선택 영역을 잘라내어 클립보드에 넣습니다.\\n잘라내기": "Cut the selection to the clipboard.\\nCut",
    "선택 영역을 복사하여 클립보드에 넣습니다.\\n복사": "Copy the selection to the clipboard.\\nCopy",
    "선택 영역을 지웁니다.\\n지우기": "Clear the selection.\\nClear",
    "지정한 텍스트를 찾습니다.\\n찾기": "Find the specified text.\\nFind",
    "클립보드 내용을 삽입합니다.\\n붙여넣기": "Insert the clipboard contents.\\nPaste",
    "특정 텍스트를 다른 텍스트로 바꿉니다.\\n바꾸기": "Replace specified text with other text.\\nReplace",
    "활성 창을 여러 개의 창으로 분할합니다.\\n분할": "Split the active window into panes.\\nSplit",
    "창 맨 아래에 아이콘을 정렬합니다.\\n아이콘 정렬": "Arrange icons along the bottom of the window.\\nArrange Icons",
    "활성 문서를 닫습니다.\\n닫기": "Close the active document.\\nClose",
    "새 문서를 만듭니다.\\n새로 만들기": "Create a new document.\\nNew",
    "다음 창으로 전환합니다.\\n다음 창": "Switch to the next window.\\nNext Window",
    "이전 창으로 전환합니다.\\n이전 창": "Switch to the previous window.\\nPrevious Window",
    "전체 문서를 선택합니다.\\n모두 선택": "Select the entire document.\\nSelect All",
    "마지막 작업을 반복합니다.\\n반복": "Repeat the last action.\\nRepeat",
    "모두 지웁니다.\\n모두 지우기": "Clear everything.\\nClear All",
    "카메라 자동이동시 타겟과의 거리": "Distance to Target During Auto Camera Movement",
    "현재 버젼 적용": "Apply Current Version",
    "적용 버젼으로 되돌리기": "Revert to Applied Version",
    "맥스 임포트 파일 생성": "Create Max Import File",
    "지형 다른이름 으로 저장": "Save Terrain As",
    "한 그리드에 몇 픽셀": "Pixels per Grid",
    "사용자 높이 조절 타입": "Height Adjustment Type",
    "타겟점 알파값": "Target Point Alpha",
    "알파 채널 교체": "Replace Alpha Channel",
    "몬스터 영역 표시": "Show Monster Regions",
    "기즈모이동감도": "Gizmo Move Sensitivity",
    "편집기준좌표": "Edit Reference Coordinates",
    "선택투명도": "Selection Transparency",
    "쉐도우 맵 블러": "Shadow Map Blur",
    "쉐도우맵 생성": "Create Shadow Map",
    "쉐도우맵 적용": "Apply Shadow Map",
    "오브젝트ID": "Object ID",
    "회전초기화": "Reset Rotation",
    "디폴트 키셋팅": "Default Key Settings",
    "자동 저장 사용": "Use Auto Save",
    "포그 오브젝트 끝 지점": "Fog Object End Distance",
    "포그 지형 끝 지점": "Fog Terrain End Distance",
    "포그 시작 지점": "Fog Start Distance",
    "원거리 클리핑": "Far Clipping",
    "백그라운드 색": "Background Color",
    "플레이어 속도": "Player Speed",
    "필드 이동 가능 지역": "Field Movement Area",
    "대상 텍스쳐": "Target Texture",
    "대상 EMR": "Target EMR",
    "포탈 오브젝트": "Portal Object",
    "포탈 대상 맵": "Portal Destination Map",
    "총 포탈 갯수": "Total Portal Count",
    "포탈 속성": "Portal Properties",
    "부활 MapID": "Respawn Map ID",
    "증가시간(s)": "Increase Duration (s)",
    "시작시간(s)": "Start Time (s)",
    "배틀태그사용여부": "Use Battle Tag",
    "배치 몬스터": "Placed Monsters",
    "몬스터 테이블": "Monster Table",
    "몬스터 배치 스케일 값": "Monster Placement Scale",
    "처치 리젠 셋팅": "Kill Respawn Settings",
    "던전 리젠 여부": "Dungeon Respawn",
    "오브젝트 패쓰 오브젝트": "Object Path Object",
    "지형 패쓰 오브젝트": "Terrain Path Object",
    "맥스 패쓰 오브젝트": "Max Path Object",
    "변화 제한값": "Change Limit",
    "위쪽 제한": "Upper Limit",
    "아래쪽 제한": "Lower Limit",
    "높이 변화 후 오브젝트 위치 갱신": "Update Object Positions After Height Changes",
    "텍스쳐 타입": "Texture Type",
    "생성 모드": "Create Mode",
    "선택 삭제": "Delete Selection",
    "위치 설정": "Set Position",
    "선택 복사": "Copy Selection",
    "오브젝트 그림자": "Object Shadow",
    "동적 그림자": "Dynamic Shadow",
    "애니메이션 오브젝트": "Animated Object",
    "속도 ( 배율 )": "Speed (Multiplier)",
    "리스트 에서 제거": "Remove from List",
    "랜덤 애니메이션 체크 시간": "Random Animation Check Time",
    "랜덤 애니메이션 속도": "Random Animation Speed",
    "지면 법선 정렬": "Align to Terrain Normal",
    "포탈 종류": "Portal Type",
    "피로도증가": "Fatigue Increase",
    "TODO: <회사 이름>": "TODO: <Company Name>",
    "TODO: <파일 설명>": "TODO: <File Description>",
    "TODO: (c) <회사 이름>.  All rights reserved.": "TODO: (c) <Company Name>. All rights reserved.",
    "TODO: <제품 이름>": "TODO: <Product Name>",
    "카메라를 리셋 시킵니다": "Reset the camera.",
    "창을 전체 화면 크기로 확대합니다.": "Maximize the window.",
    "문서를 저장할 것인지 확인하고 활성 창을 닫습니다.": "Ask whether to save the document and close the active window.",
    "창을 보통 크기로 복원합니다.": "Restore the window to its normal size.",
    "작업 목록을 활성화합니다.": "Activate the task list.",
    "이 창을 활성화합니다.": "Activate this window.",
    "창 크기를 변경합니다.": "Resize the window.",
    "창 위치를 변경합니다.": "Move the window.",
    "창을 아이콘으로 축소합니다.": "Minimize the window.",
    "다음 문서 창으로 전환합니다.": "Switch to the next document window.",
    "이전 문서 창으로 전환합니다.": "Switch to the previous document window.",
    "총 크기 ( m )": "Total Size (m)",
    "그리드 크기 ( m )": "Grid Size (m)",
    "쿼드트리 레벨": "Quadtree Level",
    "Vertex 갯수": "Vertex Count",
    "알파 채널": "Alpha Channel",
    "기본 맵": "Base Map",
    "높이 맵": "Height Map",
    "리스트 추가": "Add to List",
    "리스트 제거": "Remove from List",
    "진한 영역": "Dark Area",
    "감쇠 영역": "Fade Area",
    "감쇠 상수": "Attenuation",
    "텍스쳐": "Texture",
    "명 암 넣 기": "Add Shading",
    "명 암 빼 기": "Remove Shading",
    "맵 조밀도": "Map Density",
    "명암": "Shading",
    "새로 만들기": "New",
    "지형 로드": "Load Terrain",
    "지형 저장": "Save Terrain",
    "재 로드": "Reload",
    "패치 노트 보기": "View Patch Notes",
    "지형 합체": "Merge Terrain",
    "리스트 전부 제거": "Remove All from List",
    "랜 더 링": "Rendering",
    "속성 : ": "Properties: ",
    "사용": "Use",
    "스냅": "Snap",
    "선택 갯수": "Selection Count",
    "스케일": "Scale",
    "토글키": "Toggle Key",
    "충돌박스": "Collision Box",
    "보기": "View",
    "제자리에": "In Place",
    "기본 색상": "Base Color",
    "지형 포함": "Include Terrain",
    "회전": "Rotation",
    "이동": "Move",
    "추가": "Add",
    "수정": "Edit",
    "제거": "Remove",
    "잘라내기": "Cut",
    "회전+": "Rotate +",
    "회전 -": "Rotate -",
    "오브젝트": "Object",
    "지형": "Terrain",
    "노드 축소": "Collapse Node",
    "노드 확대": "Expand Node",
    "단축 키": "Shortcut Keys",
    "자동 저장": "Auto Save",
    "경로": "Path",
    "분": "min",
    "롤백": "Rollback",
    "언두": "Undo",
    "리두": "Redo",
    "랜더링여부": "Render Enabled",
    "탭": "Tab",
    "메뉴": "Menu",
    "파일": "File",
    "세이브": "Save",
    "로드": "Load",
    "환경": "Environment",
    "대기시간": "Wait Time",
    "기억1": "Save 1", "기억2": "Save 2", "기억3": "Save 3", "기억4": "Save 4", "기억5": "Save 5",
    "기억6": "Save 6", "기억7": "Save 7", "기억8": "Save 8", "기억9": "Save 9", "기억10": "Save 10",
    "로드1": "Load 1", "로드2": "Load 2", "로드3": "Load 3", "로드4": "Load 4", "로드5": "Load 5",
    "로드6": "Load 6", "로드7": "Load 7", "로드8": "Load 8", "로드9": "Load 9", "로드10": "Load 10",
    "전체선택": "Select All",
    "지형에붙이기": "Attach to Terrain",
    "풀스크린": "Full Screen",
    "슬라이드": "Slide",
    "소 좌": "Small Left", "소 우": "Small Right", "대 좌": "Large Left", "대 우": "Large Right",
    "리   셋": "Reset", "리 셋": "Reset", "리  셋": "Reset",
    "스카이 박스": "Skybox",
    "포그": "Fog",
    "포그 색상": "Fog Color",
    "높이": "Height",
    "셀": "Cell",
    "항상보이게": "Always Visible",
    "디지몬 보이기": "Show Digimon",
    "미니맵 생성": "Create Minimap",
    "미니 맵": "Minimap",
    "간격( cm )": "Spacing (cm)",
    "emr 파일생성": "Create EMR File",
    "저장번호": "Save Slot",
    "원래 맵": "Original Map",
    "대상 맵": "Destination Map",
    "목표 반경": "Target Radius",
    "목표 위치": "Target Position",
    "맵 로드": "Map Load",
    "포탈 ID": "Portal ID",
    "맵 이름": "Map Name",
    "맵 설명": "Map Description",
    "피로도": "Fatigue",
    "타입": "Type",
    "배경음": "Background Music",
    "디버프": "Debuff",
    "증가값": "Increase Value",
    "카메라Lv": "Camera Lv",
    "MapID 추가": "Add Map ID",
    "맵 ID 추가": "Add Map ID",
    "XG 소모 여부": "Consume XG",
    "지역 크기": "Region Size",
    "시작 지점": "Start Position",
    "시작 타입": "Start Type",
    "영역 크기": "Area Size",
    "제   거": "Remove",
    "개체 수": "Count",
    "리젠 타임": "Respawn Time",
    "디폴트 값": "Default Values",
    "기본 셋팅": "Default Settings",
    "전부제거": "Remove All",
    "몬스터 ID": "Monster ID",
    "처치 수": "Kill Count",
    "표시 시점": "Display Point",
    "이동0~4": "Move 0-4",
    "패쓰 설치": "Set Path",
    "선택 제거": "Remove Selection",
    "높이(m)": "Height (m)",
    "재설정": "Reset",
    "선택 컨트롤": "Selection Control",
    "크기": "Size",
    "위치": "Position",
    "사각형": "Rectangle", "육각형": "Hexagon", "팔각형": "Octagon",
    "전체삭제": "Delete All",
    "높이 변화값": "Height Change Value",
    "상쇠 값": "Attenuation Value", "상쇠값": "Attenuation Value",
    "셋팅": "Set",
    "해제": "Release",
    "텍스쳐 타입": "Texture Type",
    "부활 지점": "Respawn Point",
    "생성": "Create",
    "오브젝트 그림자": "Object Shadow",
    "케릭터": "Character",
    "파워": "Power",
    "거리": "Distance",
    "애니메이션": "Animation",
    "프레임": "Frame",
    "랜덤 스케일": "Random Scale",
    "랜덤 X회전": "Random X Rotation", "랜덤 Y회전": "Random Y Rotation", "랜덤 Z회전": "Random Z Rotation",
    "랜덤 Z이동": "Random Z Move",
    "배 치": "Place", "제 거": "Remove", "복 사": "Copy", "복사": "Copy", "붙이기": "Paste",
    "그룹 설치": "Group Placement",
    "갯수": "Count",
    "준비": "Ready",
    "삭제": "Delete",
    "시간(분)": "Time (min)",
    "농도": "Density",
    "주기(분)": "Interval (min)",
    "확인": "OK",
    "취소": "Cancel",
    "적용": "Apply",
}

# Runtime strings are in the C++ sources rather than the resource script.
CODE_TRANSLATIONS = {
    r".\\ToolData\\%s 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": r".\\ToolData\\%s does not exist. The tool may terminate unexpectedly.",
    r".\\ToolData\\axis.nif 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": r".\\ToolData\\axis.nif does not exist. The tool may terminate unexpectedly.",
    r".\\ToolData\\axisPlane.nif 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": r".\\ToolData\\axisPlane.nif does not exist. The tool may terminate unexpectedly.",
    r"ToolData\\RegionCylinder.nif 가 존재 하지않습니다.\n\n 강제 종료 될수 있습니다.": r"ToolData\\RegionCylinder.nif does not exist.\n\nThe tool may terminate unexpectedly.",
    r".\\ToolData\\Box100.nif 가 존재 하지않습니다.\n\n 강제 종료 될수 있습니다.": r".\\ToolData\\Box100.nif does not exist.\n\nThe tool may terminate unexpectedly.",
    "같은 단축키를 사용하는게 있습니다.\\n해당 단축키를 비우고 설정하시겠습니까?": "This shortcut is already in use.\\nClear the existing shortcut and assign this one?",
    "에디트 박스 안에 내용을 기입하여 주십시오.": "Enter a value in the edit box.",
    "메인메뉴": "Main Menu", "맵": "Map", "높이맵": "Height Map", "맵핑": "Mapping", "셀 오브젝트": "Cell Objects",
    "몬스터": "Monster", "그림자": "Shadow", "라이트": "Light", "플레이어": "Player", "패쓰엔진": "Path Engine", "날씨": "Weather", "기타": "Other",
    "맵을 생성하거나 로드하여 주십시오.": "Create or load a map first.",
    "맵 ID 를 설정 하여 주십시오.": "Set the map ID.",
    "이름": "Name", "경로": "Path", "갯수": "Count",
    "오브젝트는 현재 디렉토리의 하위 디렉토리에 존재해야만 합니다.": "The object must be located in a subdirectory of the current directory.",
    "설치된 해당 오브젝트도 전부 삭제 됩니다. 그래도 제거 하시겠습니까?": "All placed instances of this object will also be deleted. Do you want to remove it?",
    "선택된 오브젝트가 없습니다. 위 오브젝트 리스트에서 체크박스를 활성화 시켜 주십시오.": "No object is selected. Enable a checkbox in the object list above.",
    "배치할 오브젝트의 갯수는 0보다 커야 합니다.": "The number of objects to place must be greater than 0.",
    "지형 밖으로 자꾸 벗어 나므로 캔슬합니다.": "Operation cancelled because it repeatedly moves outside the terrain.",
    "맵을 세이브 해야만 미니맵 생성이 가능합니다.": "Save the map before creating a minimap.",
    "간격 (cm단위) 을 설정하여 주십시오!": "Set the spacing in centimeters.",
    "맵을 세이브 해야만 EMR 생성이 가능합니다.": "Save the map before creating an EMR file.",
    "영   역": "Region",
    "텍스쳐는 현재 디렉토리의 하위 디렉토리에 존재해야만 합니다.": "The texture must be located in a subdirectory of the current directory.",
    "평범": "Normal", "낮은부분만 변화": "Change Lower Area Only",
    "타입": "Type", "지형": "Terrain", "오브젝트 그림자": "Object Shadow", "오브젝트": "Object", "케릭터": "Character", "동적그림자": "Dynamic Shadow",
    ".\\ToolData\\%s 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": ".\\ToolData\\%s does not exist. The tool may terminate unexpectedly.",
    "맵 ID": "Map ID", "총 넓이": "Total Area", "노드 넓이": "Node Area",
    "임시 맵": "Temporary Map", "맵 아이디가 이미 존재합니다.": "The map ID already exists.", "맵 아이디가 추가 되었습니다.": "The map ID was added.",
    "선택해 주세요.": "Please select an option.", "시작 위치": "Start Position", "지역 설정": "Region Settings", "부활 위치": "Respawn Position", "진화 제한 지역": "Evolution Restriction Area", "버프 구역": "Buff Region",
    "맵 아이디를 변경 하면 저장되지 않은 Map.xls 설정 정보는 사라 집니다.\\n계속하시겠습니까?": "Changing the map ID will discard unsaved Map.xls settings.\\nDo you want to continue?",
    "맵 ID 가 0인상태에서는 사운드를 넣을수 없습니다.": "Sound cannot be added while the map ID is 0.",
    "사운드는 현재 디렉토리의 하위 디렉토리에 존재해야만 합니다.": "The sound file must be located in a subdirectory of the current directory.",
    "조건 없음": "No Condition", "디지몬 타입": "Digimon Type", "몬스터 처치": "Monster Kill", "퀘스트 완료": "Quest Complete", "아이템 사용": "Item Use", "디지몬 IDX": "Digimon IDX", "디지몬 속성": "Digimon Attribute", "진화 유형": "Evolution Type",
    "이동": "Move", "케릭터 생성": "Create Character",
    "텍스쳐 창을 초기화 합니다. 계속 하시겠습니까?": "Reset the texture window? Continue?", "첫번째 디테일 맵은 비울수 없습니다.": "The first detail map cannot be empty.",
    "배치": "Placement", "상인": "Merchant", "디지타마상인": "DigiEgg Merchant", "포탈 도우미": "Portal Helper", "용병 생성": "Mercenary Creation", "속성 상인": "Attribute Merchant", "창고": "Warehouse", "용병보관소": "Mercenary Storage", "디지코어상인": "DigiCore Merchant", "캡슐머신": "Capsule Machine", "스킬상인": "Skill Merchant", "이벤트 상점": "Event Shop", "닷츠 포탈": "DATS Portal", "커뮤니티 상점": "Community Shop", "속성 상점 상인": "Attribute Shop Merchant", "레어머신": "Rare Machine", "마스터즈 매치": "Masters Match", "수수께끼머신": "Mystery Machine", "스피릿 진화": "Spirit Evolution", "이벤트": "Event", "아이템 제작": "Item Crafting", "배틀 등록": "Battle Registration", "무한 대전 진행": "Infinite Battle Progress", "무한 대전 게시판": "Infinite Battle Board", "진화 상점 NPC": "Evolution Shop NPC", "맵툴에서속성정의안됨": "Attribute Not Defined in MapTool", ", 이동": ", Move",
    "레벨": "Level", "공격력": "Attack", "방어력": "Defense",
    "0:영역없음 1:영역(기본값) 2:이동 3:고정 4:오브젝트형": "0: No Region  1: Region (Default)  2: Move  3: Fixed  4: Object Type",
    "맵에 배치된 몬스터가 몬스터테이블( ID:%d )에 존재하지 않습니다.": "A monster placed on the map does not exist in MonsterTable (ID: %d).",
    "몬스터의 모델 데이터가 존재하지 않습니다. MonsterTableID = %d, ModelID = %d": "Monster model data does not exist. MonsterTableID = %d, ModelID = %d",
    "지형의 크기를 벋어난 몬스터가 존재합니다. MonsterTableID = %d": "A monster is outside the terrain bounds. MonsterTableID = %d",
    "모든 몬스터 제거를 계속 진행하시겠습니까?": "Do you want to remove all monsters?",
    "%s 오브젝트에는 애니메이션이 존재하지 않습니다.\\n프로퍼티 확인해주세요": "%s has no animation.\\nCheck its properties.",
    "노말포탈": "Normal Portal", "인던포탈": "Dungeon Portal", "존내포탈": "Zone Portal",
    "그림자 없음(ns)": "No Shadow (ns)", "애니메이션(ani)": "Animation (ani)", "텍스쳐 타입(tt)": "Texture Type (tt)", "카메라 알파(ca)": "Camera Alpha (ca)", "카메라 알파 픽킹(cap)": "Camera Alpha Picking (cap)", "지형 기본": "Terrain Base", "지형 기본 픽킹(tbp)": "Terrain Base Picking (tbp)", "테이블 오브젝트(table)": "Table Object (table)", "동적 그림자 적용(shadow)": "Dynamic Shadow (shadow)", "포그 없음(nf)": "No Fog (nf)", "라이트 없음(nl)": "No Light (nl)", "포탈(pt)": "Portal (pt)", "회전(ro)": "Rotation (ro)", "회전 제한(rol)": "Rotation Limit (rol)", "카메라 충돌(cc)": "Camera Collision (cc)", "오브젝트 합체(mg)": "Object Merge (mg)", "다크맵 생성(dm)": "Create Dark Map (dm)", "지형 숨은메쉬 픽킹(thp)": "Terrain Hidden Mesh Picking (thp)", "이펙트 랜더링(ef)": "Effect Rendering (ef)", "클리핑 안함(nc)": "No Clipping (nc)", "픽킹 안되게막음(nopick)": "Disable Picking (nopick)", "항상 애니메이션(awani)": "Always Animate (awani)", "랜덤 프레임 애니(anir)": "Random Frame Animation (anir)", "사운드(sd)": "Sound (sd)", "스킨(skin)": "Skin (skin)", "우선순위1 랜더링(f1)": "Priority 1 Rendering (f1)", "퀘스트 보이기(queston)": "Show Quest (queston)", "퀘스트 숨기기(questoff)": "Hide Quest (questoff)", "액션 오브젝트(act)": "Action Object (act)",
    "포탈": "Portal", "오브젝트 합체": "Object Merge", "오브젝트 창을 초기화 합니다. 계속 하시겠습니까?": "Reset the object window? Continue?",
    "위치 : %d x %d [%d,%d] [%d,%d] [%d,%d] [%d,%d]": "Position: %d x %d [%d,%d] [%d,%d] [%d,%d] [%d,%d]",
    "%s\\n\\n오브젝트의 PathEngine 선이 잘못 되었습니다.": "%s\\n\\nThe object's PathEngine line is invalid.",
    "%s\\n\\n오브젝트의 csp 파일 버젼이 예전 버전입니다.": "%s\\n\\nThe object's CSP file version is outdated.",
    "파일은 현재 디렉토리의 하위 디렉토리에 존재해야만 합니다.": "The file must be located in a subdirectory of the current directory.",
    "선택된 파일은 스카이박스 오브젝트가 아닙니다.": "The selected file is not a skybox object.",
    "오브젝트 쉐도우 체크가 활성화된 라이트가 존재하지 않습니다.": "No light has Object Shadow enabled.",
    "dm 옵션을 준 오브젝트임에도 다크맵을 가지고 있습니다.\\n%s": "This object has a dark map even though it uses the dm option.\\n%s",
    "시간": "Time", "농도": "Density", "피로도": "Fatigue", "없음": "None", "눈": "Snow", "비": "Rain",
    "총 길이를 입력하세요 !!": "Enter the total length.", "그리드 사이즈를 입력하세요 !!": "Enter the grid size.", "기본맵의 MPPG는 1이상이여야 합니다!!": "The base map MPPG must be at least 1.", "알파채널의 MPPG는 1이상이여야 합니다!!": "The alpha channel MPPG must be at least 1.",
    "Total Range 의 Width 크기가 맞지 않아 %d -> %d 로 변경": "Total Range width is invalid; changed %d -> %d.", "X축 Vertex의 산출 방법에 맞지 않아 Width 크기를 %d -> %d 로 변경": "Width does not match the X-axis vertex calculation; changed %d -> %d.", "Total Range 의 Height 크기가 맞지 않아 %d -> %d 로 변경": "Total Range height is invalid; changed %d -> %d.", "Y축 Vertex의 산출 방법에 맞지 않아 Height 크기를 %d -> %d 로 변경": "Height does not match the Y-axis vertex calculation; changed %d -> %d.", "Total Range 가 TreeLevel과 Grid Width 에 비해 너무 작다": "Total Range is too small for the Tree Level and Grid Width.",
    "한 노드에 설정된 Vertex의 갯수가 너무 많습니다. 다시 설정하여 주십시오\\n\\n현   재 갯수 : %d\\n\\n사용가능 갯수 : %d": "Too many vertices are set for one node. Adjust the settings.\\n\\nCurrent count: %d\\n\\nMaximum allowed: %d",
    "지형 쉐도우맵을 위한 이미지 데이타 생성 중입니다.": "Creating image data for the terrain shadow map.", "지형 쉐도우맵 ( 라이트맵 포함 ) 생성중 ... %d / %d": "Creating terrain shadow map (including light map) ... %d / %d", "쉐도우맵 경계선 복사중 ...": "Copying shadow map edges ...", "베이스 오브젝트에 그림자 생성중 ...": "Creating shadows for base objects ...", "쉐도우맵 생성을 위한 데이터 삭제중": "Removing data used to create the shadow map.",
    "저장 중입니다.\\n시간이 조금 걸리니 기다려주세요~!": "Saving.\\nThis may take a moment. Please wait.", "로드 중입니다.\\n시간이 조금 걸리니 기다려주세요~!": "Loading.\\nThis may take a moment. Please wait.", "헤이트 필드 생성 중입니다.": "Creating height field.", "미니 맵 생성 중입니다.": "Creating minimap.", "emr 파일 생성 중입니다.": "Creating EMR file.", "쉐도우맵 블러 중입니다. 장시만 기다려 주세요": "Blurring shadow map. Please wait a moment.",
    "타입선택": "Select Type", "몬스터킬(1)": "Monster Kill (1)", "퀘스트완료(2)": "Quest Complete (2)", "서버컨트롤(3)": "Server Control (3)",
    "텍스쳐 타입": "Texture Type", "애니메이션": "Animation",
    "선택한 오브젝트가 존재 하지 않습니다.\\n\\n리 셋 버튼을 눌러서 초기화 해 주세요.": "The selected object does not exist.\\n\\nClick Reset to initialize it.",
    ".\\ToolData\\axis.nif 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": ".\\ToolData\\axis.nif does not exist. The tool may terminate unexpectedly.",
    ".\\ToolData\\axisPlane.nif 가 존재 하지 않습니다. 비정상적으로 종료 될수 있습니다.": ".\\ToolData\\axisPlane.nif does not exist. The tool may terminate unexpectedly.",
    "Memory Dumper 가동\\n": "Memory Dumper started\\n", "뷰 창을 만들지 못했습니다.\\n": "Failed to create the view window.\\n",
    "저장된 콘피그 파일은 예전버젼 이므로\\n제거 하고 새로 만들겠습니다.": "The saved config file is outdated.\\nIt will be removed and recreated.",
    "메인 탭으로 가셔서 로드 해주세요": "Go to the Main tab and load a map.", "메인 탭으로 가셔서 세이브 해주세요": "Go to the Main tab and save the map.",
    "지형의 크기를 벋어난 NPC 가 존재합니다. NpcID = %d": "An NPC is outside the terrain bounds. NpcID = %d", "케릭터 툴에 등록 되지 않은 Npc입니다. NpcID = %d, ModelID = %d": "This NPC is not registered in Character Tool. NpcID = %d, ModelID = %d", "충돌박스 등록이 안되어 있습니다. \\n%s": "No collision box is registered.\\n%s",
    "ToolData\\RegionCylinder.nif 가 존재 하지않습니다.\\n\\n 강제 종료 될수 있습니다.": "ToolData\\RegionCylinder.nif does not exist.\\n\\nThe tool may terminate unexpectedly.", ".\\ToolData\\Box100.nif 가 존재 하지않습니다.\\n\\n 강제 종료 될수 있습니다.": ".\\ToolData\\Box100.nif does not exist.\\n\\nThe tool may terminate unexpectedly.",
    "저장된 레지스트 파일은 예전버젼 이므로\\n제거 하고 새로 만들겠습니다.": "The saved registry file is outdated.\\nIt will be removed and recreated.",
    "맵 데이터가 존재하지 않습니다.\\n\\n %s": "Map data does not exist.\\n\\n%s",
}


def main() -> None:
    data = RESOURCE.read_bytes()
    split = data.index(b"// Portugu")
    korean = data[:split].decode("cp949")
    portuguese = data[split:]

    for source, target in sorted(TRANSLATIONS.items(), key=lambda item: len(item[0]), reverse=True):
        korean = korean.replace(source, target)

    korean = korean.replace("// Coreano (Coreia do Sul) resources", "// English (United States) resources")
    korean = korean.replace("defined(AFX_TARG_KOR)", "defined(AFX_TARG_ENG)")
    korean = korean.replace("LANGUAGE LANG_KOREAN, SUBLANG_DEFAULT", "LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US")
    korean = korean.replace("LANGUAGE 18, 1", "LANGUAGE 9, 1")

    remaining = re.findall(r'"([^"\r\n]*[\uac00-\ud7a3][^"\r\n]*)"', korean)
    if remaining:
        raise RuntimeError("Untranslated resource captions: " + "; ".join(dict.fromkeys(remaining)))

    RESOURCE.write_bytes(korean.encode("cp949") + portuguese)
    print(f"Translated {len(TRANSLATIONS)} resource captions to English.")

    code_root = RESOURCE.parent
    changed_files = 0
    for path in code_root.rglob("*"):
        if path.suffix.lower() not in {".cpp", ".h"}:
            continue

        raw = path.read_bytes()
        encoding = None
        for candidate in ("utf-8", "cp949"):
            try:
                source = raw.decode(candidate)
                encoding = candidate
                break
            except UnicodeDecodeError:
                continue
        if encoding is None:
            continue

        translated = source
        for source_text, target_text in sorted(CODE_TRANSLATIONS.items(), key=lambda item: len(item[0]), reverse=True):
            translated = translated.replace(f'"{source_text}"', f'"{target_text}"')

        if translated != source:
            path.write_bytes(translated.encode(encoding))
            changed_files += 1

    print(f"Translated runtime strings in {changed_files} C++ source files.")


if __name__ == "__main__":
    main()
