import os
import subprocess
from PIL import Image

SOURCE = "input.png"

def test_isolation():
    if not os.path.exists(SOURCE):
        print(f"Error: Could not find {SOURCE}")
        return

    # We use the width that crashed previously for the test
    killer_width = 974
    print(f"\n--- Testing Isolation (Width: {killer_width}px) ---")

    # Step 1: Create the 'Killer' PNG
    with Image.open(SOURCE) as img:
        temp_rgba = img.convert("RGBA").resize((killer_width, 623))
        temp_rgba.save("killer_input.png")
        print(f"1. Prepared RGBA file: killer_input.png ({killer_width}x623)")

    # Step 2: Test via libavif CLI
    print("2. Attempting conversion via libavif CLI (avifenc)...", end=" ", flush=True)
    cli_cmd = ["avifenc", "killer_input.png", "cli_output.avif", "--jobs", "1", "--speed", "6"]
    try:
        res = subprocess.run(cli_cmd, capture_output=True, text=True)
        if res.returncode == 0:
            print("✅ CLI SUCCESS (libavif might be safe, Pillow bridge suspect)")
        else:
            print(f"❌ CLI FAILED (Return code {res.returncode})")
    except Exception as e:
        # If it triggers 'corrupted size', the subprocess will return a negative signal (6)
        print(f"💥 CLI CRASHED: {e}")

    # Step 3: Test via Pillow
    print("3. Attempting conversion via Pillow...", end=" ", flush=True)
    try:
        with Image.open("killer_input.png") as p_img:
            p_img.save("pillow_output.avif", speed=6)
            print("✅ Pillow SUCCESS")
    except Exception as e:
        print(f"❌ Pillow FAILED/CRASHED")


if __name__ == "__main__":
    test_isolation()
