import tex2img
from pathlib import Path
from struct import unpack
from PIL import Image
import sys

def process_pkm_to_png(input_path, output_path):
    """将PKM文件转换为PNG"""
    try:
        data = input_path.read_bytes()
        if data[:4] != b"PKM ":
            return None
        
        _format = int.from_bytes(data[6:8], "big")
        width = int.from_bytes(data[12:14], "big")
        height = int.from_bytes(data[14:16], "big")
        
        outdata = tex2img.decompress_etc(data[16:], width, height, _format)
        if len(outdata) / width / height == 4:
            im = Image.frombytes("RGBA", (width, height), outdata)
        else:
            im = Image.frombytes("RGB", (width, height), outdata)
        
        return im
    except Exception as e:
        print(f"PKM转换出错: {str(e)}")
        return None

def apply_alpha_channel(image):
    """将图片下半部分作为alpha通道应用到上半部分"""
    try:
        width, height = image.size
        
        # 如果高度是奇数，直接返回原图
        if height % 2 != 0:
            return image
        
        half_height = height // 2
        
        # 提取上半部分（RGB部分）
        upper_half = image.crop((0, 0, width, half_height))
        
        # 提取下半部分（alpha通道）
        lower_half = image.crop((0, half_height, width, height))
        
        # 将下半部分转换为灰度图作为alpha通道
        alpha_channel = lower_half.convert('L')
        
        # 确保上半部分是RGBA模式
        if upper_half.mode != 'RGBA':
            upper_half = upper_half.convert('RGBA')
        
        # 将alpha通道应用到上半部分
        upper_half.putalpha(alpha_channel)
        
        return upper_half
    except Exception as e:
        print(f"应用alpha通道出错: {str(e)}")
        return None

def process_file(input_path, output_path):
    """处理单个文件"""
    # 首先转换PKM到PNG
    png_image = process_pkm_to_png(input_path, None)
    if png_image is None:
        return False
    
    # 应用alpha通道处理（如果是奇数高度会自动跳过处理）
    final_image = apply_alpha_channel(png_image)
    if final_image is None:
        return False
    
    # 保存结果
    final_image.save(output_path, format='PNG')
    return True

def batch_process(input_dir, output_dir):
    """批量处理目录中的所有PKM文件"""
    output_dir = Path(output_dir)
    output_dir.mkdir(exist_ok=True)
    
    for item in Path(input_dir).rglob("*.pkm"):
        relative_path = item.relative_to(input_dir)
        output_path = output_dir / relative_path.with_suffix(".png")
        
        # 确保输出目录存在
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        if output_path.exists():
            print(f"已存在，跳过: {output_path}")
            continue
        
        if process_file(item, output_path):
            print(f"处理成功: {output_path}")
        else:
            print(f"处理失败: {item}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("使用方法: python pkm2png_Alpha.py <输入目录> <输出目录>")
        sys.exit(1)
    
    input_dir = sys.argv[1]
    output_dir = sys.argv[2]
    
    batch_process(input_dir, output_dir)