import json
from pathlib import Path


def replace_json_text(root_folder: str | Path, target_str: str, replace_str: str):
    root_path = Path(root_folder)
    total_replaced = 0
    scanned_files = 0

    def transform_value(value):
        nonlocal total_replaced
        if isinstance(value, str) and target_str in value:
            new_val = value.replace(target_str, replace_str)
            # 상세 로그가 필요하면 아래 주석 해제 (속도 저하 원인)
            # print(f"  Changed: {value[:30]}... -> {new_val[:30]}...")
            total_replaced += 1
            return new_val, True
        return value, False

    # 재귀 탐색 함수
    def traverse_and_replace(data):
        changed = False

        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, (dict, list)):
                    if traverse_and_replace(value):
                        changed = True
                else:
                    new_val, is_replaced = transform_value(value)
                    if is_replaced:
                        data[key] = new_val
                        changed = True

        elif isinstance(data, list):
            for i, item in enumerate(data):
                if isinstance(item, (dict, list)):
                    if traverse_and_replace(item):
                        changed = True
                else:
                    new_val, is_replaced = transform_value(item)
                    if is_replaced:
                        data[i] = new_val
                        changed = True

        return changed

    print(f"🚀 탐색 시작: {root_path}")

    for file_path in root_path.rglob('*.json'):
        scanned_files += 1
        try:
            text = file_path.read_text(encoding='utf-8')
            json_data = json.loads(text)

            # 변경 사항이 있을 때만 쓰기 작업 수행
            if traverse_and_replace(json_data):
                file_path.write_text(
                    json.dumps(json_data, indent=2, ensure_ascii=False),
                    encoding='utf-8'
                )
                print(f"✅ 수정됨: {file_path.relative_to(root_path)}")

        except (json.JSONDecodeError, UnicodeDecodeError):
            print(f"❌ 파싱/인코딩 에러: {file_path.relative_to(root_path)}")
        except Exception as e:
            print(f"⚠️ 에러 발생: {file_path.relative_to(root_path)} -> {e}")

    print("=" * 30)
    print(f"📂 스캔 파일: {scanned_files}개")
    print(f"🔄 총 변경 값: {total_replaced}건")
    print("완료.")
