#!/usr/bin/env python3
"""Convert chess-sprite.png to a WoW-compatible TGA file.

Resizes to 768x256 (power-of-2, 6x2 grid of 128x128 cells).
Makes the light background transparent.
Writes uncompressed 32-bit RGBA TGA.
"""

import struct
import os
from PIL import Image

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

def png_to_tga(input_name, output_name, target_w, target_h):
    input_path = os.path.join(SCRIPT_DIR, input_name)
    output_path = os.path.join(SCRIPT_DIR, output_name)

    img = Image.open(input_path).convert("RGBA")
    print(f"  Source: {input_name} ({img.width}x{img.height})")

    # Resize to target dimensions
    img = img.resize((target_w, target_h), Image.LANCZOS)

    # Make near-white/light-gray background transparent
    pixels = img.load()
    for y in range(target_h):
        for x in range(target_w):
            r, g, b, a = pixels[x, y]
            # Light background pixels (near-white/light-gray) become transparent
            if r > 200 and g > 200 and b > 200:
                pixels[x, y] = (r, g, b, 0)

    # Write TGA
    with open(output_path, 'wb') as f:
        # TGA header (18 bytes)
        f.write(struct.pack('<B', 0))       # ID length
        f.write(struct.pack('<B', 0))       # Color map type
        f.write(struct.pack('<B', 2))       # Image type (uncompressed true-color)
        f.write(struct.pack('<5B', 0,0,0,0,0))  # Color map spec
        f.write(struct.pack('<H', 0))       # X origin
        f.write(struct.pack('<H', 0))       # Y origin
        f.write(struct.pack('<H', target_w))  # Width
        f.write(struct.pack('<H', target_h))  # Height
        f.write(struct.pack('<B', 32))      # Bits per pixel
        f.write(struct.pack('<B', 8))       # Image descriptor (top-left origin + 8 alpha bits)

        # Pixel data (BGRA, top-to-bottom)
        for y in range(target_h):
            for x in range(target_w):
                r, g, b, a = pixels[x, y]
                f.write(struct.pack('<4B', b, g, r, a))

    print(f"  Created: {output_name} ({target_w}x{target_h})")


if __name__ == "__main__":
    print("Converting chess sprite to TGA...")
    png_to_tga("chess-sprite.png", "chess_pieces.tga", 768, 256)
    print("Done!")
