#!/usr/bin/env python3
"""
Usage:
  python3 recount_files.py <number> (<directory>)
"""

import os
from pathlib import Path
import sys
import re
from termcolor import colored

def main():
    if len(sys.argv) == 2:
        dir = Path(os.getcwd())
    elif (len(sys.argv) == 3):
        dir = Path(sys.argv[2])
    else:
        print("Usage: recount_files.py <number> (<directory>)")
        sys.exit(1)

    import subprocess
    subprocess.run(["python", "/home/honney/.bin/tracker.py", "add", "recount_files"])

    number = int(sys.argv[1])

    # Pattern matches numbers (int or float) at the start (Group 1) 
    # and captures the rest of the filename (Group 2)
    pattern = re.compile(r'^(\d+(?:\.\d+)?)(.*)')

    files_data = []
    for f in dir.iterdir():
        if f.is_file():
            match = pattern.match(f.stem)
            if match:
                # Store a tuple: (Path object, numeric_string, rest_of_filename)
                files_data.append((f, match.group(1), match.group(2)))

    if not files_data:
        print("No matching files found.")
        sys.exit(0)

    # Sort files based on the numeric part cast to a float
    files_data = sorted(files_data, key=lambda x: float(x[1]))

    min_num_float = float(files_data[0][1])
    
    # Calculate padding based on the longest numeric string
    max_len = max(len(files_data[-1][1]), 2)

    failed = []

    for f, num_str, rest in files_data:
        # Determine if the current prefix is a float or an int
        if '.' not in num_str:
            delta = int(num_str) - int(min_num_float)
            new_num_str = f"{delta+number:0{max_len}d}"
        else:
            delta = float(num_str) - min_num_float
            new_num_str = f"{delta+number:0{max_len+2}.1f}"
            
        # Recombine: New Number + Rest of Name + Extension
        new_file_name = Path(f"{f.parent}/{new_num_str}{rest}{f.suffix}")
        
        if not new_file_name.is_file():
            print(
                colored("Renamed: ", "green") +
                colored(str(f.parent)+"/", "cyan") +
                colored("[", "white") +
                colored(f.name, "red") +
                colored(" -> ", "white") +
                colored(new_file_name.name, "green") +
                colored("]", "white")
            )
            f.rename(new_file_name)
        else:
            failed.append([f, new_file_name])
            print(colored(f"{new_file_name.name} already exists. Retrying later", "red"))

    failed2 = []
    if failed:
        failed.reverse()
        for f, new_file_name in failed:
            if not new_file_name.is_file():
                print(
                    colored("Renamed: ", "green") +
                    colored(str(f.parent)+"/", "cyan") +
                    colored("[", "white") +
                    colored(f.name, "red") +
                    colored(" -> ", "white") +
                    colored(new_file_name.name, "green") +
                    colored("]", "white")
                )
                f.rename(new_file_name)
            else:
                failed2.append([f, new_file_name])
                print(colored(f"{new_file_name.name} already exists. Aborting", "red"))

    if failed2:
        print(colored("Failed to rename the following files:", "red"))
        for f, new_file_name in failed2:
            print(colored(f"{new_file_name.name} already exists. Aborting", "red"))

if __name__ == "__main__":
    main()