# Copyright 2025 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import sys

for path in sys.argv[1:]:
    print(f"Converting {path}")
    with open(path, "r") as fp:
        lines = fp.read().splitlines(keepends=False)
        metadata_lines = []
        in_metadata_block = False
        delim = lines[0].split()[0] + " "
        lines_iter = iter(lines)
        while True:
            line = next(lines_iter)
            if line == f"{delim}This lockfile was autogenerated by Pants. To regenerate, run:":
                next(lines_iter)
                cmd = next(lines_iter)[len(delim):].strip()
            if line == f"{delim}--- END PANTS LOCKFILE METADATA ---":
                remaining_lines = list(lines_iter)
                break
            elif in_metadata_block:
                metadata_lines.append(line[len(delim):])
            elif line == f"{delim}--- BEGIN PANTS LOCKFILE METADATA: DO NOT EDIT OR REMOVE ---":
                in_metadata_block = True
        metadata_lines.insert(1, f'"description": "This lockfile was generated by Pants. To regenerate, run: {cmd}",')
        metadata = "\n".join(metadata_lines) + "\n"
        with open(f"{path}.metadata", "w") as fp:
            fp.write(metadata)
        with open(path, "w") as fp:
            fp.write("\n".join(remaining_lines).strip() + "\n")
