Option Explicit

Dim fso, folderPath, tsvPath, tsvFile
Set fso = CreateObject("Scripting.FileSystemObject")

' --- Configure Paths ---
folderPath = "\\asstr-mirror\WWW\www.asstr-mirror.org\files\Collections\Alt.Sex.Stories.Moderated"
tsvPath    = folderPath & "\smaller_duplicates.tsv"

If Not fso.FolderExists(folderPath) Then
    MsgBox "Source folder not found: " & folderPath, 16, "Error"
    WScript.Quit
End If

' Create the TSV file to act as a deletion log
Set tsvFile = fso.CreateTextFile(tsvPath, True)
tsvFile.WriteLine "Folder_Path" & vbTab & "Base_Name" & vbTab & "Action_Taken" & vbTab & "File_Path" & vbTab & "Size_Bytes"

' Start the recursive process
ProcessFolder fso.GetFolder(folderPath)

tsvFile.Close
MsgBox "Process complete. Files deleted and mastered. Log written to:" & vbCrLf & tsvPath, 64, "Success"

' --- Main Recursive Subroutine ---
Sub ProcessFolder(currentFolder)
    Dim fileGroups, file, baseName, currentSize, subFolder, isCopy, copyNum
    Set fileGroups = CreateObject("Scripting.Dictionary")
    fileGroups.CompareMode = 1 ' Case-insensitive

    ' Pass 1: Find the absolute master file for each base name in THIS folder
    For Each file In currentFolder.Files
        If file.Path <> tsvPath Then
            baseName = CleanFileName(file.Name, isCopy, copyNum)
            currentSize = file.Size
            
            If Not fileGroups.Exists(baseName) Then
                ' Store: Array(Size, IsCopy, CopyNumber, FilePath)
                fileGroups.Add baseName, Array(currentSize, isCopy, copyNum, file.Path)
            Else
                Dim maxValues
                maxValues = fileGroups(baseName) 
                
                Dim replaceMaster
                replaceMaster = False
                
                If currentSize > maxValues(0) Then
                    replaceMaster = True
                ElseIf currentSize = maxValues(0) Then
                    ' Tie-breaker 1: Prefer a clean file over a copy designator
                    If maxValues(1) = True And isCopy = False Then
                        replaceMaster = True
                    ' Tie-breaker 2: If both are copies, prefer the lower copy number
                    ElseIf maxValues(1) = True And isCopy = True Then
                        If copyNum < maxValues(2) Then
                            replaceMaster = True
                        End If
                    End If
                End If
                
                If replaceMaster Then
                    fileGroups(baseName) = Array(currentSize, isCopy, copyNum, file.Path)
                End If
            End If
        End If
    Next

    ' Pass 2: Delete smaller/copy files and rename the remaining master files
    Dim baseKey, finalMaster, masterFile, masterNewPath, masterFolder
    
    For Each file In currentFolder.Files
        If file.Path <> tsvPath Then
            baseName = CleanFileName(file.Name, isCopy, copyNum)
            finalMaster = fileGroups(baseName)
            
            ' If this file is NOT the chosen master file, delete it
            If file.Path <> finalMaster(3) Then
                Dim reason
                If file.Size < finalMaster(0) Then
                    reason = "Deleted (Smaller Size)"
                Else
                    reason = "Deleted (Copy Designator Tie)"
                End If
                
                tsvFile.WriteLine currentFolder.Path & vbTab & baseName & vbTab & reason & vbTab & vbTab & "del " & Chr(34) & file.Path & Chr(34) & vbTab & vbTab & file.Size
                
                ' Delete the file (True forces deletion of read-only files)
                fso.DeleteFile file.Path, True
            End If
        End If
    Next

    ' Pass 3: Handle renaming of the remaining master files if they have a copy designator
    For Each baseKey In fileGroups.Keys
        finalMaster = fileGroups(baseKey) ' Array(Size, IsCopy, CopyNumber, FilePath)
        
        ' If the master file exists and was flagged as having a copy designator
        If finalMaster(1) = True Then
            If fso.FileExists(finalMaster(3)) Then
                Set masterFile = fso.GetFile(finalMaster(3))
                masterFolder = fso.GetParentFolderName(masterFile.Path)
                masterNewPath = fso.BuildPath(masterFolder, baseKey)
                
                ' Guard clause: Only rename if the clean file target name isn't somehow already taken
                If Not fso.FileExists(masterNewPath) Then
                    tsvFile.WriteLine masterFolder & vbTab & baseKey & vbTab & "Renamed Master to Clean Name" & vbTab & masterFile.Path & vbTab & masterFile.Size
                    masterFile.Name = baseKey
                Else
                    tsvFile.WriteLine masterFolder & vbTab & baseKey & vbTab & "Rename Skipped (Target File Existed)" & vbTab & masterFile.Path & vbTab & masterFile.Size
                End If
            End If
        End If
    Next

    ' Recursive Step: Repeat the process for each subfolder independently
    For Each subFolder In currentFolder.SubFolders
        ProcessFolder subFolder
    Next
End Sub

' --- Helper Function to Strip Copy Designators and Extract Details ---
Function CleanFileName(fileName, ByRef outIsCopy, ByRef outCopyNum)
    Dim regEx, matches, ext, nameWithoutExt
    
    ext = fso.GetExtensionName(fileName)
    nameWithoutExt = fso.GetBaseName(fileName)
    
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.IgnoreCase = True
    regEx.Global = True
    
    ' Pattern extracts trailing digits inside parentheses or standard copy formats
    regEx.Pattern = "\s*[-_]?\s*\(?Copy\s*(\d*)\)?\s*$|\s*\((\d+)\)\s*$"
    
    outIsCopy = regEx.Test(nameWithoutExt)
    outCopyNum = 0 ' Default for non-copies
    
    If outIsCopy Then
        Set matches = regEx.Execute(nameWithoutExt)
        If matches(0).SubMatches(0) <> "" Then
            outCopyNum = CInt(matches(0).SubMatches(0))
        ElseIf matches(0).SubMatches(1) <> "" Then
            outCopyNum = CInt(matches(0).SubMatches(1))
        Else
            outCopyNum = 1 ' Default for plain " - Copy"
        End If
    End If
    
    nameWithoutExt = regEx.Replace(nameWithoutExt, "")
    
    If ext <> "" Then
        CleanFileName = nameWithoutExt & "." & ext
    Else
        CleanFileName = nameWithoutExt
    End If
End Function
