"""
LShipParts 贴图颜色替换脚本
将 #4f5358 (RGB: 79,83,88) 替换为 #ececec (RGB: 236,236,236)
保留原始 Alpha 通道，不修改其他任何像素
"""

import os
import shutil
from PIL import Image

# 源目录和目标目录
SOURCE_DIR = r"f:\KSP mod testing\LShipParts"
TARGET_DIR = r"f:\KSP mod testing\LShipParts_White"

# 颜色定义
OLD_COLOR = (79, 83, 88)      # #4f5358
NEW_COLOR = (236, 236, 236)   # #ececec

def process_image(filepath):
    """处理单个 PNG 图片，替换指定颜色"""
    try:
        img = Image.open(filepath).convert("RGBA")
        pixels = img.load()
        width, height = img.size
        modified = False

        for y in range(height):
            for x in range(width):
                r, g, b, a = pixels[x, y]
                if (r, g, b) == OLD_COLOR:
                    pixels[x, y] = (NEW_COLOR[0], NEW_COLOR[1], NEW_COLOR[2], a)
                    modified = True

        if modified:
            img.save(filepath)
            return True
        return False
    except Exception as e:
        print(f"  [错误] 处理失败: {e}")
        return False

def main():
    print("=" * 60)
    print("LShipParts 贴图颜色替换工具")
    print(f"将 RGB{OLD_COLOR} (#4f5358) 替换为 RGB{NEW_COLOR} (#ececec)")
    print("=" * 60)

    # 1. 复制整个目录
    print(f"\n[1/3] 复制目录...")
    print(f"  源目录: {SOURCE_DIR}")
    print(f"  目标目录: {TARGET_DIR}")

    if os.path.exists(TARGET_DIR):
        print(f"  目标目录已存在，正在删除...")
        shutil.rmtree(TARGET_DIR)

    shutil.copytree(SOURCE_DIR, TARGET_DIR)
    print(f"  复制完成!")

    # 2. 扫描所有 PNG 文件
    print(f"\n[2/3] 扫描 PNG 文件...")
    png_files = []
    for root, dirs, files in os.walk(TARGET_DIR):
        for f in files:
            if f.lower().endswith('.png'):
                png_files.append(os.path.join(root, f))

    print(f"  找到 {len(png_files)} 个 PNG 文件")

    # 3. 处理所有 PNG 文件
    print(f"\n[3/3] 开始处理贴图...")
    modified_count = 0
    for i, filepath in enumerate(png_files, 1):
        rel_path = os.path.relpath(filepath, TARGET_DIR)
        print(f"  [{i}/{len(png_files)}] {rel_path}", end="")
        if process_image(filepath):
            modified_count += 1
            print(" ✓ (已修改)")
        else:
            print(" - (无变化)")

    # 4. 输出统计
    print("\n" + "=" * 60)
    print(f"处理完成!")
    print(f"  总 PNG 文件数: {len(png_files)}")
    print(f"  已修改文件数: {modified_count}")
    print(f"  输出目录: {TARGET_DIR}")
    print("=" * 60)

if __name__ == "__main__":
    main()
