#!/usr/bin/env python3
"""sheet_to_spriteframes.py - turn a sprite sheet into a Godot 4 SpriteFrames .tres

Each row of the sheet is one animation. Example:
  python3 sheet_to_spriteframes.py slime_all.png res://art/slime_all.png 16 16 \
      idle:4:6:loop hop:6:10:loop hurt:2:8 death:5:10 > slime_spriteframes.tres
Arguments: sheet file (to read nothing but check it exists), its res:// path,
frame width, frame height, then one name:frames:fps[:loop] per row, top to bottom.
MIT licence - Slime Forge.
"""
import os
import sys


def main(argv):
    if len(argv) < 6:
        sys.exit(__doc__)
    sheet, res_path, fw, fh = argv[1], argv[2], int(argv[3]), int(argv[4])
    if not os.path.exists(sheet):
        sys.exit(f"sheet not found: {sheet}")
    subs, anims = [], []
    for row, spec in enumerate(argv[5:]):
        parts = spec.split(":")
        name, count, fps = parts[0], int(parts[1]), float(parts[2])
        loop = len(parts) > 3 and parts[3] == "loop"
        ids = []
        for i in range(count):
            sid = f"AtlasTexture_{name}_{i}"
            subs.append(f'[sub_resource type="AtlasTexture" id="{sid}"]\n'
                        f'atlas = ExtResource("1_sheet")\n'
                        f'region = Rect2({i * fw}, {row * fh}, {fw}, {fh})\n')
            ids.append(sid)
        frames = ", ".join('{\n"duration": 1.0,\n"texture": SubResource("%s")\n}' % s for s in ids)
        anims.append('{\n"frames": [%s],\n"loop": %s,\n"name": &"%s",\n"speed": %s\n}'
                     % (frames, "true" if loop else "false", name, repr(fps)))
    out = [f'[gd_resource type="SpriteFrames" load_steps={len(subs) + 2} format=3]\n',
           f'[ext_resource type="Texture2D" path="{res_path}" id="1_sheet"]\n']
    out += subs
    out.append("[resource]\nanimations = [%s]\n" % ", ".join(anims))
    sys.stdout.write("\n".join(out))


if __name__ == "__main__":
    main(sys.argv)
