import os
import filecmp
import shutil
import hashlib


INI_FILE = "merged.ini"
DISABLED_INI_FILE = "DISABLEDmerged_duporigin.ini"
FILE_RECORD = "file_record.txt"

def generate_hash(filepath):
    sha256_hash = hashlib.sha256()
    with open(filepath, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()


def remove_duplicates():
    print("Starting duplicate removal process...")
    file_details = {}  
    duplicates = []

    for dirpath, dirnames, filenames in os.walk("."):
        for filename in filenames:
            if filename == FILE_RECORD or filename.endswith('.ini') or 'DISABLED' in filename:
                continue
            path = os.path.join(dirpath, filename)
            file_size = os.path.getsize(path)
            file_hash = generate_hash(path)
            
            if (file_size, file_hash) not in file_details:
                file_details[(file_size, file_hash)] = path
            else:
                duplicates.append(path)

    with open(FILE_RECORD, 'w') as f:
        for duplicate in duplicates:
            f.write(f"{duplicate}={file_details[(os.path.getsize(duplicate), generate_hash(duplicate))]}\n")
            os.remove(duplicate)

    print("Duplicate removal completed.")
    
    return duplicates


def restore_files():
    if not os.path.exists(FILE_RECORD):
        print(f"Error: {FILE_RECORD} not found!")
        return

    with open(FILE_RECORD, 'r') as f:
        lines = f.readlines()
        for line in lines:
            duplicate, original = line.strip().split('=')
            shutil.copy2(original, duplicate)

    os.remove(FILE_RECORD)
    if os.path.exists(INI_FILE):
        os.remove(INI_FILE)
    if os.path.exists(DISABLED_INI_FILE):
        os.rename(DISABLED_INI_FILE, INI_FILE)

if __name__ == '__main__':
    print("Script started.")
    choice = input("Choose action (remove/restore): ").strip().lower()

    if choice == 'remove':
        duplicates = remove_duplicates()

        if os.path.exists(INI_FILE):
            with open(INI_FILE, 'r', encoding='utf-8') as f:
                content = f.read()
                for duplicate in duplicates:
                    with open(FILE_RECORD, 'r') as record:
                        lines = record.readlines()
                        for line in lines:
                            dup_path, orig_path = line.strip().split('=')
                            if dup_path == duplicate:
                                content = content.replace(duplicate, orig_path)
                                break

            if os.path.exists(DISABLED_INI_FILE):
                os.remove(DISABLED_INI_FILE) 

            os.rename(INI_FILE, DISABLED_INI_FILE)

            with open(INI_FILE, 'w', encoding='utf-8') as f:
                f.write(content)

            print(f"Renamed original {INI_FILE} to {DISABLED_INI_FILE} and created a new {INI_FILE}.")
        else:
            print(f"Error: {INI_FILE} not found!")
    elif choice == 'restore':
        restore_files()
    else:
        print("Invalid action. Exiting.")

