from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
PATCH_FILE = BASE_DIR / "patch_list.txt"

def parse_patch_file(patch_file: Path):
    if not patch_file.exists():
        raise FileNotFoundError(f"패치 목록 파일이 없습니다: {patch_file}")

    text = patch_file.read_text(encoding="utf-8")
    blocks = text.split("===PATCH===")
    patches = []

    for block in blocks:
        block = block.strip()
        if not block:
            continue

        if "===END===" not in block:
            print("[경고] ===END=== 가 없는 패치 블록은 건너뜀")
            continue

        block = block.split("===END===", 1)[0]
        if "file:" not in block or "find:" not in block or "replace:" not in block:
            print("[경고] file/find/replace 형식이 맞지 않는 패치 블록은 건너뜀")
            continue

        file_part = block.split("file:", 1)[1].split("find:", 1)[0]
        find_part = block.split("find:", 1)[1].split("replace:", 1)[0]
        replace_part = block.split("replace:", 1)[1]

        # 맨 앞과 맨 뒤 공백을 제거하여 일치 확률을 높임
        patches.append({
            "file": file_part.strip(),
            "find": find_part.strip(),
            "replace": replace_part.strip(),
        })

    return patches

def apply_patch(file_path_str: str, find_text: str, replace_text: str):
    # 절대 경로 그대로 시도하고, 없으면 상대 경로로 다시 시도
    target_file = Path(file_path_str)
    if not target_file.exists():
        target_file = BASE_DIR / file_path_str
    
    if not target_file.exists():
        print(f"[실패] 파일 없음: {target_file}")
        return False

    try:
        original = target_file.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        print(f"[실패] UTF-8로 읽을 수 없음: {target_file}")
        return False

    # 원본 파일에서 정확한 위치를 찾기 위해 strip() 처리된 텍스트로 비교
    if find_text not in original:
        print(f"[실패] 찾을 내용 없음: {target_file}")
        # 디버깅용: 실제 파일 내용 중 일부 출력
        return False

    patched = original.replace(find_text, replace_text, 1)
    target_file.write_text(patched, encoding="utf-8")

    print(f"[완료] 패치 적용: {target_file}")
    return True

def main():
    try:
        patches = parse_patch_file(PATCH_FILE)
    except Exception as e:
        print(f"오류 발생: {e}")
        return

    print(f"총 패치 개수: {len(patches)}")
    success_count = 0
    fail_count = 0

    for index, patch in enumerate(patches, start=1):
        print(f"\n========== {index}번 패치 ==========")
        result = apply_patch(patch["file"], patch["find"], patch["replace"])
        if result:
            success_count += 1
        else:
            fail_count += 1

    print(f"\n========== 전체 결과 ==========")
    print(f"성공: {success_count}")
    print(f"실패: {fail_count}")

if __name__ == "__main__":
    main()