"""
Texture Optimization Script for ATC25_KnaackJobsitePack
Converts PNG to DDS and resizes oversized DDS files
Requires: pip install Pillow
"""
from PIL import Image
import os
import struct

TEXTURES_DIR = "textures"
MAX_SIZE_MB = 12
PNG_FILES = ["8539177_orig.png", "Decals.png", "Logo.png", "Piano89.png"]
OVERSIZED_DDS = ["ElectriciansHammer_albedo.dds", "Tools_BaseColor.dds"]

def get_dds_dimensions(filepath):
    """Read DDS header to get dimensions"""
    with open(filepath, 'rb') as f:
        magic = f.read(4)
        if magic != b'DDS ':
            return None
        f.read(4)  # skip size
        f.read(4)  # skip flags
        height = struct.unpack('<I', f.read(4))[0]
        width = struct.unpack('<I', f.read(4))[0]
        return width, height

def convert_png_to_dds_compatible(png_path):
    """Convert PNG to format ready for DDS conversion"""
    img = Image.open(png_path)
    
    # Ensure power of 2 dimensions
    w, h = img.size
    new_w = 2 ** (w - 1).bit_length()
    new_h = 2 ** (h - 1).bit_length()
    
    if (new_w, new_h) != (w, h):
        img = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
        print(f"  Resized {png_path}: {w}x{h} -> {new_w}x{new_h}")
    
    # Save as uncompressed TGA (easier to convert to DDS)
    output = png_path.replace('.png', '_converted.tga')
    img.save(output, 'TGA')
    print(f"  ✓ Converted to TGA: {output}")
    return output

def resize_dds_source(dds_path):
    """Create guidance for resizing DDS files"""
    size_mb = os.path.getsize(dds_path) / (1024 * 1024)
    dims = get_dds_dimensions(dds_path)
    
    if dims:
        w, h = dims
        print(f"\n{os.path.basename(dds_path)}:")
        print(f"  Current: {w}x{h} ({size_mb:.2f} MB)")
        
        # Calculate target resolution
        target_w, target_h = w // 2, h // 2
        estimated_size = size_mb / 4
        
        while estimated_size > MAX_SIZE_MB and target_w > 512:
            target_w //= 2
            target_h //= 2
            estimated_size /= 4
        
        print(f"  Recommended: {target_w}x{target_h} (~{estimated_size:.2f} MB)")
        print(f"  Action: Re-export from source at {target_w}x{target_h} with DXT1/DXT5 compression")

def main():
    print("=== Texture Optimization Tool ===\n")
    
    # Convert PNG files
    print("1. PNG to TGA Conversion:")
    for png in PNG_FILES:
        png_path = os.path.join(TEXTURES_DIR, png)
        if os.path.exists(png_path):
            try:
                convert_png_to_dds_compatible(png_path)
            except Exception as e:
                print(f"  ✗ Error converting {png}: {e}")
        else:
            print(f"  ⚠ Not found: {png}")
    
    # Analyze oversized DDS files
    print("\n2. Oversized DDS Files Analysis:")
    for dds in OVERSIZED_DDS:
        dds_path = os.path.join(TEXTURES_DIR, dds)
        if os.path.exists(dds_path):
            resize_dds_source(dds_path)
        else:
            print(f"  ⚠ Not found: {dds}")
    
    print("\n=== Next Steps ===")
    print("1. Use a DDS converter tool (GIMP, Paint.NET, or texconv.exe) to:")
    print("   - Convert .tga files to .dds with DXT1/DXT5 compression")
    print("   - Re-export oversized DDS files at recommended resolutions")
    print("2. Replace original files with optimized versions")
    print("3. Delete .tga temporary files")

if __name__ == "__main__":
    main()
