#!/usr/bin/env python3
"""
Convert an old single-mesh text animation file to the new multi-mesh text format.

The only structural difference is that the new format wraps the mesh block
between these two extra headers before the "===Vertices:" line:

    === TOTAL MESHES TO EXPORT: 1 ===
    === Mesh Object: Body ===

Usage:
    python convert_old_anim_to_new.py <input.txt> <output.txt> [mesh_name]

If mesh_name is omitted, "Body" is used.
"""

import sys


def convert(input_path, output_path, mesh_name="Body"):
    with open(input_path, 'r', encoding='utf-8', errors='replace') as f:
        lines = f.readlines()

    # Find the first "===Vertices:" line -- that's where the bone block ends
    # and the mesh block begins in the old format.
    insert_at = None
    for i, line in enumerate(lines):
        if line.lstrip().startswith("===Vertices:"):
            insert_at = i
            break

    if insert_at is None:
        raise RuntimeError("Could not find '===Vertices:' line in input file")

    header_lines = [
        "=== TOTAL MESHES TO EXPORT: 1 ===\n",
        f"=== Mesh Object: {mesh_name} ===\n",
    ]

    out_lines = lines[:insert_at] + header_lines + lines[insert_at:]

    with open(output_path, 'w', encoding='utf-8') as out:
        out.writelines(out_lines)

    print(f"Converted: {input_path} -> {output_path} (mesh name: {mesh_name})")


if __name__ == '__main__':
    if len(sys.argv) not in (3, 4):
        print(f"Usage: {sys.argv[0]} <input.txt> <output.txt> [mesh_name]")
        sys.exit(1)

    mesh_name = sys.argv[3] if len(sys.argv) == 4 else "Body"
    convert(sys.argv[1], sys.argv[2], mesh_name)
