#
# rainbow-timestamp.pl — paint each printed line's leading timestamp with
# the rotating rainbow palette from rainbow.pl, so every successive line
# advances the colour phase. Each individual timestamp is itself a
# gradient across its own characters (HH:MM -> five different colours).
#
# Drops into ~/.irssi/scripts/autorun/; loads automatically on irssi start.
#

use strict;
use warnings;
use vars qw($VERSION %IRSSI);
use Irssi;

$VERSION = '0.1';
%IRSSI = (
    authors     => 'dissimulo',
    contact     => 'connect+gitea@dustin-williams.com',
    name        => 'rainbow-timestamp',
    description => 'Rotating-rainbow timestamps (same palette/logic as rainbow.pl).',
    license     => 'GNU GPLv2 or later',
);

# mIRC colour palette — identical to rainbow.pl:
#   4 = light red, 8 = yellow, 9 = light green,
#   11 = light cyan, 12 = light blue, 13 = light magenta
my @colors    = ('4', '8', '9', '11', '12', '13');
my $last_color = 0;
my $colorrep  = 2;   # how many chars share each colour before advancing

sub make_colors {
    my ($string) = @_;
    my $out  = '';
    my $last = $last_color;
    for (my $c = 0; $c < length($string); $c++) {
        my $char = substr($string, $c, 1);
        $last++;
        my $color = int($last / $colorrep) % scalar(@colors);
        $out .= "\003" . sprintf('%02d', $colors[$color]);
        $out .= ($char eq ',') ? "\," : $char;
    }
    $last_color += 2;   # advance phase so the next call starts shifted
    return $out;
}

# Hook 'print text' — fires once per window line, with the fully-rendered
# text (including the leading timestamp if info_eol is off, which is the
# default). We match a leading HH:MM or HH:MM:SS, recolour it, and pass
# the line back through signal_continue with the rest of the text intact.
Irssi::signal_add('print text', sub {
    my ($dest, $text, $stripped) = @_;
    return unless defined $text;

    # Strip any existing colour codes from just the prefix to find the
    # raw timestamp (irssi's theme abstract may have wrapped it).
    # Match (optional colour prefix) + HH:MM[:SS] + (optional colour suffix) + space
    if ($text =~ /^((?:\003\d{1,2}(?:,\d{1,2})?)*)(\d{2}:\d{2}(?::\d{2})?)((?:\017|\003)?)(\s)/) {
        my $pre   = $1;       # existing colour codes before the timestamp
        my $ts    = $2;       # the timestamp itself
        my $post  = $3;       # colour reset (if any)
        my $sep   = $4;       # whitespace between ts and rest
        my $rest  = substr($text, length($pre) + length($ts) + length($post) + length($sep));

        my $coloured = make_colors($ts) . "\017";   # \017 = reset colour
        Irssi::signal_continue($dest, $coloured . $sep . $rest, $stripped);
    }
});
