#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use File::stat;
use Cwd 'abs_path';  # To get absolute paths

# Hash to store file information
my %files;

# Function to process each file
sub process_file {
    my $file = $File::Find::name;  # Full path of the file (could be relative)

    # Only process mp3 files
    return unless $file =~ /\.mp3$/i;

    # Get the absolute path of the file to avoid any relative path issues
    my $abs_file = abs_path($file);
    unless ($abs_file) {
        warn "Could not get absolute path for $file: $!";
        return;
    }

    # Get the file's size and timestamps
    my $file_stat = stat($abs_file);

    # Error handling for stat
    unless ($file_stat) {
        warn "Could not stat $abs_file: $!";
        return;
    }

    my $size = $file_stat->size;
    my $mtime = $file_stat->mtime;

    # Extract the basename of the file (filename without directory path)
    my ($filename) = $abs_file =~ /([^\/]+)$/;

    # If a file with the same name and size exists, check the timestamp
    if (exists $files{$filename} && $files{$filename}{size} == $size) {
        my $existing_file = $files{$filename}{path};
        my $existing_mtime = $files{$filename}{mtime};

        # Print if the timestamps differ
        if ($mtime != $existing_mtime) {
            print "Duplicate found:\n";
            print "File 1: $existing_file (Size: $size bytes, Timestamp: $existing_mtime)\n";
            print "File 2: $abs_file (Size: $size bytes, Timestamp: $mtime)\n\n";
        }
    } else {
        # Otherwise, store the file details in the hash
        $files{$filename} = {
            path  => $abs_file,
            size  => $size,
            mtime => $mtime,
        };
    }
}

# Find all mp3 files in the current directory and subdirectories
find(\&process_file, '.');

print "Done searching for duplicates.\n";

