#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use File::Copy;
use File::Basename;
use Cwd 'abs_path';

# Configuration
my $source_dir = "ShowsNew";      # Folder with original files
my $target_dir = "Shows";            # Where to save modified files
my $pattern_to_replace = '~/Documents/FreeShow';
my $expansion = 'Documents/FreeShow'; # We'll expand ~ to user's home

# Create target directory if it doesn't exist
unless (-d $target_dir) {
    mkdir $target_dir or die "Cannot create directory '$target_dir': $!";
}

# Get the user's home directory
my $home_dir = $ENV{HOME} || $ENV{USERPROFILE} || die "Cannot determine home directory";

# Create the expanded path
my $expanded_path = "$home_dir/$expansion";

# Normalize paths for the current OS
$expanded_path =~ s!/+!/!g;  # Remove duplicate slashes

print "Expanding paths from: $pattern_to_replace\n";
print "To: $expanded_path\n";
print "Processing files in: $source_dir\n";
print "Saving to: $target_dir\n\n";

# Process all files in the source directory
opendir(my $dh, $source_dir) or die "Cannot open directory '$source_dir': $!";
my @files = readdir($dh);
closedir($dh);

my $processed_count = 0;

foreach my $file (@files) {
    # Skip directories and hidden files
    next if $file =~ /^\./;
    next if -d "$source_dir/$file";
    
    my $source_file = "$source_dir/$file";
    my $target_file = "$target_dir/$file";
    
    print "Processing: $file\n";
    
    # Read the file
    open(my $in, '<:encoding(UTF-8)', $source_file) or do {
        warn "Cannot read file '$source_file': $!";
        next;
    };
    
    # Create output file
    open(my $out, '>:encoding(UTF-8)', $target_file) or do {
        warn "Cannot write file '$target_file': $!";
        close $in;
        next;
    };
    
    # Process each line
    while (my $line = <$in>) {
        # Replace the pattern with expanded path
        $line =~ s!\Q$pattern_to_replace\E!$expanded_path!g;
        print $out $line;
    }
    
    close $in;
    close $out;
    
    $processed_count++;
    print "  -> Saved as: $target_file\n";
}

print "\nDone! Processed $processed_count files.\n";
