#!/usr/bin/perl -w

use v5.38;
use experimental 'multidimensional', 'for_list', 'builtin';
use builtin 'indexed';
use List::Util;
use Y::AoC::Task;
$; = ';';
# t;

my @map = map { chomp; [ split //, ".$_." ] } <>;
push @map, [ ('.') x @{ $map[0]} ];
unshift @map, [ ('.') x @{$map[0]} ];
my $xmax = $#{$map[0]};
my $ymax = $#map;

my ($sx, $sy);
for my $x (0 .. $xmax) {
for my $y (0 .. $ymax) {
	next if $map[$y][$x] ne 'S';
	$sx = $x; $sy = $y;
} }


my %dirs = (
	'|' => [ 0, -1,  0,  1],
	'-' => [-1,  0,  1,  0],
	'J' => [-1,  0,  0, -1],
	'L' => [ 1,  0,  0, -1],
	'F' => [ 1,  0,  0,  1],
	'7' => [-1,  0,  0,  1],
);


if ($map[$sy][$sx-1] eq '-' && $map[$sy][$sx+1] eq '-') {
	$map[$sy][$sx] = '-';
} elsif ($map[$sy+1][$sx] eq '|' && $map[$sy-1][$sx] eq '|') {
	$map[$sy][$sx] = '|';
} elsif ($map[$sy][$sx-1] eq '-' && $map[$sy-1][$sx] eq '|') {
	$map[$sy][$sx] = 'J';
} elsif ($map[$sy][$sx-1] eq '-' && $map[$sy+1][$sx] eq '|') {
	$map[$sy][$sx] = '7';
} elsif ($map[$sy][$sx+1] eq '-' && $map[$sy-1][$sx] eq '|') {
	$map[$sy][$sx] = 'L';
} elsif ($map[$sy][$sx+1] eq '-' && $map[$sy+1][$sx] eq '|') {
	$map[$sy][$sx] = 'F';
}

say "starting at $sx, $sy $map[$sy][$sx]";
my %seen;
my $len = 0;
my ($px, $py);
while (!$seen{$sx,$sy}++) {
	my @d = $dirs{ $map[$sy][$sx] }->@*;
	if (!defined($px) || ($px != $d[0] || $py != $d[1])) {
		$sx += $d[0];
		$sy += $d[1];
		$px = -$d[0];
		$py = -$d[1];
	} else {
		$sx += $d[2];
		$sy += $d[3];
		$px = -$d[2];
		$py = -$d[3];
	}
	++$len;
}

say "loop len ", $len/2;

my $sum;
for my $x (0 .. $xmax) {
	my $in = 0;
	my $left = 0;
	for my $y (0 .. $ymax) {
		if ($seen{$x,$y}) {
			my $pt = $map[$y][$x];
			if ($pt eq '-') {
				$in = !$in;
			} elsif ($pt eq '7') {
				$left = 1;
			} elsif ($pt eq 'F') {
				$left = -1;
			} elsif ($pt eq 'J') {
				if ($left == -1) {
					$in = !$in;
				}
			} elsif ($pt eq 'L') {
				if ($left == 1) {
					$in = !$in;
				}
			}
			say "$x $y in $in left $left";
		} elsif ($in) {
			say "$x $y inside";
			$sum++;
		}
	}
}

say $sum;
