#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use Image::Size;
use GD;
use POSIX qw(strftime);
use List::Util qw(sum);

# Hash to store image data by year
my %year_data;

# Function to process each image file
sub process_image {
    my $file = $_;
    my $full_path = $File::Find::name;
    
    # Check if file has image extension
    return unless $file =~ /\.(jpg|jpeg|png|gif)$/i;
    
    # Get file modification time
    my $mtime = (stat($full_path))[9];
    my $year = (localtime($mtime))[5] + 1900;
    
    # Get image dimensions
    my ($width, $height) = imgsize($full_path);
    
    # Skip if we couldn't get dimensions
    return unless defined $width && defined $height;
    
    # Calculate aspect ratio
    my $aspect_ratio = $height > 0 ? $width / $height : 0;
    
    # Store data
    push @{$year_data{$year}}, {
        width => $width,
        height => $height,
        aspect_ratio => $aspect_ratio,
        file => $full_path
    };
    
    print "Processed: $full_path ($width x $height, aspect: " . sprintf("%.2f", $aspect_ratio) . ", year: $year)\n";
}

# Get directory from command line or use current directory
my $directory = $ARGV[0] || '.';

print "Scanning directory: $directory\n";
print "=" x 50 . "\n";

# Find and process all image files
find(\&process_image, $directory);

# Calculate yearly averages
my %yearly_averages;

foreach my $year (keys %year_data) {
    my @images = @{$year_data{$year}};
    next if @images == 0;
    
    my $avg_width = sum(map { $_->{width} } @images) / @images;
    my $avg_height = sum(map { $_->{height} } @images) / @images;
    my $avg_aspect = sum(map { $_->{aspect_ratio} } @images) / @images;
    
    $yearly_averages{$year} = {
        avg_width => $avg_width,
        avg_height => $avg_height,
        avg_aspect => $avg_aspect,
        count => scalar @images
    };
    
    print "\nYear $year: " . @images . " images\n";
    print "  Average resolution: " . sprintf("%.0f x %.0f", $avg_width, $avg_height) . "\n";
    print "  Average aspect ratio: " . sprintf("%.2f", $avg_aspect) . "\n";
}

# Exit if no data found
unless (keys %yearly_averages) {
    print "No image files found!\n";
    exit 1;
}

print "\n" . "=" x 50 . "\n";
print "Creating visualization...\n";

# Create the visualization
my @years = sort { $a <=> $b } keys %yearly_averages;
my $min_year = $years[0];
my $max_year = $years[-1];
my $year_span = $max_year - $min_year + 1;

# Image dimensions
my $img_width = 1200;
my $img_height = 600;
my $margin = 100;
my $chart_width = $img_width - 2 * $margin;
my $chart_height = $img_height - 2 * $margin;

# Create image
my $img = GD::Image->new($img_width, $img_height);

# Allocate colors
my $white = $img->colorAllocate(255, 255, 255);
my $black = $img->colorAllocate(0, 0, 0);
my $gray = $img->colorAllocate(128, 128, 128);
my $blue = $img->colorAllocate(0, 100, 200);

# Fill background
$img->fill(0, 0, $white);

# Draw main horizontal line (x-axis)
my $axis_y = $img_height - $margin - 50;
$img->line($margin, $axis_y, $img_width - $margin, $axis_y, $black);

# Calculate positions and draw for each year
my $max_rect_height = 150; # Maximum height for rectangles

# Find the maximum aspect ratio to normalize rectangle sizes
my $max_aspect = 0;
my $max_resolution = 0;

foreach my $year (@years) {
    my $data = $yearly_averages{$year};
    $max_aspect = $data->{avg_aspect} if $data->{avg_aspect} > $max_aspect;
    my $resolution = $data->{avg_width} * $data->{avg_height};
    $max_resolution = $resolution if $resolution > $max_resolution;
}

foreach my $year (@years) {
    my $data = $yearly_averages{$year};
    
    # Calculate x position
    my $year_offset = $year - $min_year;
    my $x_pos = $margin + ($year_offset / ($year_span - 1)) * $chart_width;
    
    # Draw tick mark
    $img->line($x_pos, $axis_y - 5, $x_pos, $axis_y + 5, $black);
    
    # Draw year label
    my $year_str = "$year";
    my $text_width = length($year_str) * 6; # Approximate character width
    $img->string(gdSmallFont, $x_pos - $text_width/2, $axis_y + 10, $year_str, $black);
    
    # Calculate rectangle dimensions based on aspect ratio
    # Normalize the rectangle size based on resolution
    my $resolution = $data->{avg_width} * $data->{avg_height};
    my $size_factor = sqrt($resolution / $max_resolution) * 0.8 + 0.2; # Scale between 0.2 and 1.0
    
    my $rect_height = $max_rect_height * $size_factor;
    my $rect_width = $rect_height * $data->{avg_aspect};
    
    # Limit width to prevent overlap
    $rect_width = 80 if $rect_width > 80;
    
    # Draw rectangle above the tick
    my $rect_x1 = $x_pos - $rect_width/2;
    my $rect_y1 = $axis_y - 80 - $rect_height;
    my $rect_x2 = $x_pos + $rect_width/2;
    my $rect_y2 = $axis_y - 80;
    
    $img->rectangle($rect_x1, $rect_y1, $rect_x2, $rect_y2, $black);
    $img->fill($rect_x1 + 1, $rect_y1 + 1, $blue);
    
    # Add resolution label above rectangle
    my $res_label = sprintf("%.0fx%.0f", $data->{avg_width}, $data->{avg_height});
    my $label_width = length($res_label) * 6;
    $img->string(gdSmallFont, $x_pos - $label_width/2, $rect_y1 - 15, $res_label, $black);
    
    # Add aspect ratio label
    my $aspect_label = sprintf("%.2f", $data->{avg_aspect});
    my $aspect_width = length($aspect_label) * 6;
    $img->string(gdSmallFont, $x_pos - $aspect_width/2, $rect_y2 + 5, $aspect_label, $gray);
}

# Add title
my $title = "Average Image Resolutions and Aspect Ratios by Year";
my $title_width = length($title) * 8;
$img->string(gdMediumBoldFont, ($img_width - $title_width)/2, 20, $title, $black);

# Add legend
$img->string(gdSmallFont, $margin, 50, "Rectangle size represents relative resolution", $gray);
$img->string(gdSmallFont, $margin, 65, "Rectangle width/height ratio represents aspect ratio", $gray);
$img->string(gdSmallFont, $margin, 80, "Numbers above: average resolution, below: aspect ratio", $gray);

# Save the image
open(my $fh, '>', 'imageyears.png') or die "Cannot create imageyears.png: $!";
binmode $fh;
print $fh $img->png;
close $fh;

print "Visualization saved as 'imageyears.png'\n";
print "Summary:\n";
print "  Years covered: $min_year - $max_year\n";
print "  Total images processed: " . sum(map { $yearly_averages{$_}->{count} } keys %yearly_averages) . "\n";
