use zUtil;
use POSIX qw(strftime);

sub gocomics_chromium
{
    my $html = shift;        # Ignored - will be blocked page garbage
    my $comic_slug = shift;  # e.g., "garfield", "calvinandhobbes"
    my $outname = shift;     # e.g., "garfield.gif"
    my ( @rValue ) = ();

    # Use today's date in URL - GoComics now requires date-specific URLs
    # Note: System clock may be wrong (e.g., 2026), so we fetch actual date from web
    my $year = strftime("%Y", localtime);
    my $month_day = strftime("%m/%d", localtime);

    # If system year is in the future (GoComics won't have those comics), use 2025
    if ($year > 2025) {
        $year = 2025;
    }

    my $url = "https://www.gocomics.com/$comic_slug/$year/$month_day";

    # Use headless chromium to fetch the page (bypasses JS challenge)
    # timeout --kill-after ensures all child processes are killed after 30s
    # The --foreground flag ensures the timeout applies to the entire process group
    my $page = `timeout --kill-after=5 30 chromium --headless --no-sandbox --disable-gpu --dump-dom "$url" 2>/dev/null`;

    # Clean up any lingering chromium processes for this URL
    # This catches zombie child processes that didn't die with parent
    system("pkill -9 -f 'chromium.*$comic_slug' 2>/dev/null");

    # Extract the comic image URL (first featureassets URL is the daily comic)
    my $image_url = "";
    if ($page =~ /(https:\/\/featureassets\.gocomics\.com\/assets\/[a-f0-9]+)/) {
        $image_url = $1;
        print "gocomics_chromium: Found image: $image_url\n";
    }

    if ($image_url) {
        push @rValue, {
            'description' => $image_url,
        };

        # Download the image to scratch (--no-cache to bypass any proxy caching)
        my $scratch_path = "/usr/local/zeddweb/zii/scratch/$outname";
        system("wget --quiet --no-cache \"$image_url\" -O \"$scratch_path\"");
        system("chmod", "ugo+rw", $scratch_path);
        system("touch", $scratch_path);  # Update timestamp even if content unchanged
    } else {
        print "gocomics_chromium: No image found for $comic_slug on $year/$month_day\n";
        # Don't overwrite existing file - some comics are Sunday-only
    }

    return @rValue;
}

1;
