# on Windows: perl .\geo_stream.pl -f <log_file_name> [-i <seconds>]

=begin
monitor memory useage in powershell:
# Get the Perl process ID
$proc = Get-Process perl

# Monitor it
while ($true) {
    $proc.Refresh()
    "{0:HH:mm:ss} | {1} MB" -f (Get-Date), ([math]::Round($proc.WorkingSet64 / 1MB, 2))
    Start-Sleep 2
}
=cut

use 5.34.0;
use lib '.';
use GeoStream;
use Pod::Usage;
use Getopt::Long;
use Data::Printer;
use Time::HiRes qw(sleep);
use autodie qw(open close seek);

use utf8;
use open ':std', ':utf8';
binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
STDOUT->autoflush(1);
STDERR->autoflush(1);

# Handle interrupt gracefully
$SIG{INT} = sub { 
    say STDERR "\nShutting down...";
    exit 0;
};

# Command line options
my %opts;
GetOptions(
    'file|f=s'     => \$opts{file},
	'test|t'       => \$opts{test},
    'interval|i=f' => \$opts{interval} // 0.5,
); # p %opts;
pod2usage("Error: Log file required\n") unless $opts{file};

my $geo = GeoStream->new( test_output => $opts{test} );

monitor_log($opts{file}, $opts{interval});

sub monitor_log {
    my ($log_file, $interval) = @_;
    my $last_size = -s $log_file // die "Cannot access $log_file: $!\n";

	# if script opened after x-plane started, will die unless simulation start time set:
	unless ( $geo->sim_start_time ) {
		open my $fh, '<', $log_file;
		while (<$fh>) { # say $_;
            next unless  $_ =~ m/X-Plane Started on (.*)/i;
            $geo->set_sim_start_time($_);
        }
		close $fh;
	}

    while (1) {
        eval {
            my $size = -s $log_file;
            if ($size > $last_size) {
                open my $fh, '<', $log_file;
                seek($fh, $last_size, 0);
                while (<$fh>) { # say $_;
                    $geo->decode_line($_);
                }
                close $fh;
                $last_size = $size;
            }
        };
        warn "Error reading $log_file: $@" if $@;
        sleep $interval;
    }
}

__END__

=head1 NAME

geo_stream_live.pl - Monitor X-Plane log file for geographic data

=head1 SYNOPSIS

    geo_stream_live.pl -f <logfile> [-i <interval>]

    Options:
        -f, --file      Log file to monitor (required)
        -i, --interval  Check interval in seconds (default: 0.5)
        -h, --help      Show this help

=head1 DESCRIPTION

Monitors an X-Plane log file in real-time and processes geographic data.
Handles Windows file streaming limitations.

=cut
