"""
Project: Filling in the Gaps
Page 248
"""

import re
import sys
import argparse
from pathlib import Path

parser = argparse.ArgumentParser(description="Renumeración de archivos")
parser.add_argument("-p", "--pattern", type=str, default="*.*")
parser.add_argument("-i", "--input", type=Path, default=Path.cwd())
parser.add_argument("--add-gap", type=int, default=0)
args = parser.parse_args()
files = []

if not args.input.exists():
    print("ERROR: el input no existe")
    sys.exit(1)

for path in list(args.input.glob(args.pattern)):
    try:
        index = int(re.sub(r"^\D+", "", path.stem))
    except Exception:
        index = 0
    files.append({"index": index, "path": path})

if len(files) == 0:
    print(f"No se encontraron archivo con el patrón '{args.pattern}'")
    sys.exit()

files = sorted(files, key=lambda f: f["index"])
biggest = str(files[-1]["index"])
curr_index = 1
for file in files:
    if args.add_gap == curr_index:
        curr_index += 1
    num = str(curr_index)
    zeros = "0" * (len(biggest) - len(num))
    index = f"{zeros}{num}"
    curr_index += 1
    if re.search(r"\d+", file["path"].stem):
        parts = re.split(r"\d+", file["path"].stem)
        file_name = parts[0] + index + "".join(parts[1:])
    else:
        file_name = file["path"].stem + index
    new_path = file["path"].parent / f"{file_name}{file['path'].suffix}"
    print(f"{file['path']} => {new_path}")
    # file["path"].rename(new_path)  # PELIGRO: renombrará el archivo
