#!/usr/bin/env perl

package heavens_above_mag;

use 5.010;

use strict;
use warnings;

use Cache::FileCache;
use File::Basename qw{ dirname };
use File::Temp 0.15;
use Getopt::Long 2.33 qw{ :config auto_version };
use HTML::TreeBuilder;
use HTTP::Date qw{ time2str };
use JSON;
use LWP::UserAgent;
use Pod::Usage;
use YAML 1.25 qw{ Dump Load };

our $VERSION = '0.135_01';

use constant CACHE_DIR	=> 'meta/cache';

use constant MARK	=> '# $$';
use constant MARK_BEGIN	=> join ' ', MARK, 'BEGIN';
use constant MARK_BEGIN_MAG	=> join ' ', MARK_BEGIN, 'magnitude_table';
use constant MARK_END	=> join ' ', MARK, 'END';

use constant MODIFY_FILE	=> 'lib/Astro/Coord/ECI/TLE.pm';
use constant MODIFY_DIR		=> dirname( MODIFY_FILE );

use constant REF_HASH	=> ref {};

use constant AST_URL	=> 'https://celestrak.org/NORAD/elements/gp.php?GROUP=ast&FORMAT=JSON';
use constant VISUAL_URL	=> 'https://celestrak.org/NORAD/elements/gp.php?GROUP=visual&FORMAT=JSON';

my %opt = (
    age	=> 86_400,	# One day, in seconds
    delay	=> 5,	# Seconds
);
{
    my $config = get_config();
    foreach ( qw{ age delay user_agent } ) {
	defined $config->{$_}
	    and $opt{$_} = $config->{$_};
    }
}

unless ( caller ) {	# We're a modulino.
    GetOptions( \%opt,
	qw{ age=i celestrak! config=s delay=i open!
	update! user_agent|user-agent=s verbose! },
	clear	=> sub { $opt{_cache_action} = sub {
		get_cache_object()->clear();
	    } },
	purge	=> sub { $opt{_cache_action} = sub {
		get_cache_object()->purge();
	    } },
	touch	=> sub { $opt{_cache_action} = sub {
		my $cache = get_cache_object();
		foreach my $key ( $cache->get_keys() ) {
		    my $obj = $cache->get_object( $key )
			or next;
		    $cache->set( $key, $obj->get_data() );
		}
		return;
	    } },
	help	=> sub { pod2usage( { -verbose => 2 } ) },
    ) or pod2usage( { -verbose => 0 } );

    $opt{celestrak} //= $opt{update};

    if ( my $code = $opt{_cache_action} ) {
	$code->();
	@ARGV
	    or $opt{celestrak}
	    or exit;
    }

    if ( $opt{celestrak} ) {
	@ARGV and pod2usage( {
		-message	=> 'Arguments forbidden with --celestrak',
		-verbose	=> 0,
	    } );
	process_celestrak();
    } else {
	@ARGV or pod2usage( {
		-message	=> 'Arguments required unless --celestrak, --clear, or --purge specified',
		-verbose	=> 0,
	    } );

	if ( $opt{open} ) {
	    process_open( @ARGV );
	} else {
	    process_perl( @ARGV );
	}
    }
}

# This mess exists because Heavens-Above enclosed multiple table rows in
# a <span>..</span>. This is a standards violation which (e.g.) Firefox
# tolerates, but HTML::TreeBuilder's parse emits such spans as empty
# tags at some indeterminate point in the parse. Unless this is fixed,
# we will have to just hope they continue to honor the Accept-Language
# request header, or that the default language remains English.
sub find_td_by_content {
    my ( $tree, $re ) = @_;

    my $ele = $tree->look_down( _tag => 'td', sub {
	    ( local $_ ) = $_[0]->content_list();
	    defined
		or return $_;
	    return $_ =~ $re;
	} )
	or return;

    my ( $val ) = $ele->content_list();
    $val =~ s/ \A \s+ //smx;
    $val =~ s/ \s+ .* //smx;
    return $val;
}

sub delay {
    state $next_time = 0;
    my $time = time;
    $time < $next_time
	and sleep( $next_time - $time );
    $next_time = time() + $opt{delay};
    return;
}

sub find_span {
    my ( $tree, $id ) = @_;
    my $ele = $tree->look_down( _tag => 'span', id => $id )
	or die "Bug - span id='$id' not found";
    my ( $val ) = $ele->content_list();
    $val =~ s/ \A \s+ //smx;
    $val =~ s/ \s+ \z //smx;
    return $val;
}

sub get_cache_object {
    state $cache = Cache::FileCache->new( {
	    auto_purge_interval	=> $opt{age},
	    cache_root		=> CACHE_DIR,
	    default_expires_in	=> $opt{age},
	} );
    return $cache;
}

sub get_config {
    state $config;
    $config
	and return $config;

    my $path = $opt{config} // 'meta/magnituderc';
    if ( open my $fh, '<:encoding(utf-8)', $path ) {
	$config = {
	    source	=> $path,
	};
	local $_ = undef;	# while(<>) does not localize
	while ( <$fh> ) {
	    s/ \s+ \z //smx;
	    s/ \# .* //smx;
	    s/ \A \s+ //smx;
	    length $_
		or next;
	    state $valid_name = { map { $_ => 1 } qw{
		age delay source user_agent
	    } };
	    my ( $name, $value ) = split /\s*=\s*/, $_, 2;
	    if ( $valid_name->{$name} ) {
		$config->{$name} = $value;
	    } elsif ( $name =~ m/ \A [0-9]+ \z /smx ) {
		$config->{$name} = {
		    mag		=> $value,
		    source	=> $config->{source},
		};
	    } else {
		warn "Ignoring '$_'\n";
	    }
	}
	close $fh;
	delete $config->{source};
	return $config;
    } elsif ( defined $opt{config} ) {
	die "Failed to open $path: $!\n";
    }
}

sub get_cached {
    my ( $url ) = @_;

    state $cache = get_cache_object();

    my $resp;
    unless ( $resp = $cache->get( $url ) ) {
	delay();
	state $ua = do {
	    my @arg;
	    defined $opt{user_agent}
		and push @arg, agent => $opt{user_agent};
	    LWP::UserAgent->new( @arg );
	};
	$resp = $ua->get( $url );
	$resp->is_success()
	    or die "Failed to fetch $url: ", $resp->status_line();
	my ( $last_modified ) = $resp->header( 'Last-Modified' );
	unless ( defined $last_modified ) {
	    # The Celestrak API does not provide this, so we do the best
	    # we can.
	    $last_modified = time2str( time );
	    $resp->header( 'Last-Modified' => $last_modified );
	}
	$cache->set( $url, $resp );
    }
    return $resp;
}

sub get_file {
    my ( $fn ) = @_;
    local $/ = undef;
    open my $fh, '<:encoding(utf-8)', $fn
	or die "Unable to open $fn: $!\n";
    my $content = <$fh>;
    close $fh;
    return $content;
}

sub get_html {
    my ( $oid ) = @_;
    my $url = heavens_above_url( $oid );
    my $resp = get_cached( $url );
    return $resp->decoded_content();
}

sub heavens_above_url {
    my ( $oid ) = @_;
    $oid =~ m/ \A [0-9]+ \z /smx
	or die "OID '$oid' not numeric\n";
    return sprintf 'https://www.heavens-above.com/SatInfo.aspx?satid=%05d', $oid;
}

sub open_file_for_output {
    my ( $path ) = @_;
    open my $fh, '>:encoding(utf-8)', $path
	or die "Failed to open $path: $!\n";
    return $fh;
}

sub print_perl {
    # my ( $oid, $name, $mag ) = @_;
    my ( $sat ) = @_;
    if ( defined $sat->{mag} ) {
	printf "  '%d' => %5.1f, # %s\n", $sat->{id}, $sat->{mag},
	    "$sat->{name}, from $sat->{source}";
    } else {
	printf "  '%d' => undef, # %s has no recorded magnitude\n",
	    $sat->{id}, $sat->{name};
    }
    return;
}

sub process_celestrak {
    my $visual = get_cached( VISUAL_URL );
    my $ast = get_cached( AST_URL );
    my ( $last_modified ) = $visual->header( 'Last-Modified' );
    my ( @preamble, @postamble );
    my @options = qw{ --celestrak };
    if ( $opt{update} ) {
	open my $fh, '<:encoding(utf-8)', MODIFY_FILE
	    or die "Failed to open @{[ MODIFY_FILE ]}: $!\n";
	local $_ = undef;
	while ( <$fh> ) {
	    push @preamble, $_;
	    $_ eq MARK_BEGIN_MAG . "\n"
		and last;
	}
	defined $_
	    or die q/Failed to find '/, MARK_BEGIN_MAG, q/' in /,
		MODIFY_FILE, "\n";
	push @preamble, "\n";
	while ( <$fh> ) {
	    $_ eq MARK_END . "\n"
		and last;
	}
	defined $_
	    or die q/Failed to find '/, MARK_END, q/' in /, MODIFY_FILE, "\n";
	push @postamble, "\n", $_;
	while ( <$fh> ) {
	    push @postamble, $_;
	}
	close $fh;
	push @options, qw{ --update };
    }

    my $fh;
    {
	$opt{update}
	    # and local *STDOUT = open_file_for_output( MODIFY_FILE );
	    and local *STDOUT = $fh = File::Temp->new( DIR => MODIFY_DIR );
	binmode STDOUT, ':encoding(utf-8)';
	print @preamble;
	print <<"EOD";
# The following is all the Celestrak visual list plus all the Celestrak
# ast satellites that have magnitudes in Heavens Above. These data are
# generated by the following:
#
#   \$ tools/heavens-above-mag @options
#
# Last-Modified: @{[ $last_modified // 'unknown' ]}

%magnitude_table = (
EOD

	my %oid;
	parse_visual( $visual, \%oid );
	parse_visual( $ast, \%oid );
	process_perl( \%oid, sort { $a <=> $b } keys %oid );
	say ');';
	print @postamble;
    }
    if ( $fh ) {
	close $fh;
	$fh->unlink_on_destroy( 0 );
	unless ( rename "$fh", MODIFY_FILE ) {
	    my $err = $!;
	    unlink "$fh";
	    die "Unable to rename '$fh' to @{[ MODIFY_FILE ]}: $err\n";
	}
    }
    return;
}

sub parse_visual {
    my ( $resp, $oid ) = @_;
    $oid ||= {};

    my $data = decode_json( $resp->decoded_content() );
    foreach my $obj ( @$data ) {
	local $_ = $obj->{OBJECT_NAME};
	s/ \A \s+ //smx;	# Paranoia
	s/ \s+ \z //smx;	# Ditto
	$oid->{$obj->{NORAD_CAT_ID}} = $_;
    }

    return $oid;
}

# Used by xt/author/magnitude_status
sub process_get {
    my ( $spec ) = @_;
    my @rslt;
    process_parse(
	sub {
	    push @rslt, @_;
	    return;
	},
	$spec,
    );
    return @rslt;
}

sub process_open {
    my @arg = @_;
    require Browser::Open;
    my $cmd = Browser::Open::open_browser_cmd();
    foreach my $oid ( @arg ) {
	my $url = heavens_above_url( $oid );
	system { $cmd } $cmd, $url;
    }
    return;
}

sub process_parse {
    my ( $handler, @arg ) = @_;
    my $name_table = ref( $arg[0] ) eq REF_HASH ? shift @arg : {};
    foreach my $spec ( @arg ) {
	my $get = $spec =~ m/ \A [0-9]+ \z /smx ? \&get_html : \&get_file;
	my $tree = HTML::TreeBuilder->new_from_content( $get->( $spec ) );
	# print $tree->as_HTML();
	# Should return a <span>..</span> containing the OID
	my $oid = find_span( $tree, 'ctl00_cph1_lblSatID' );
	# Should return a <span>..</span> containing the name
	my $name = $name_table->{$oid} //
	    find_span( $tree, 'ctl00_cph1_lblOIGName' );
	# We would like to look for id ctl00_cph1_lblBrightness here, but it
	# contains table rows (which it should not), so HTML::TreeBuilder
	# spits it out any old where. Sometimes before the table, sometimes
	# in the middle of it (but still empty). So we just have to hope the
	# default display is English.
	my $mag = find_td_by_content(
	    $tree, qr< \b at \s+ 1000 \s* km \s+ distance \b >smxi );

	my $source;
	state $config = get_config();

	if ( defined $mag ) {
	    $source = 'Heavens Above';
	} elsif ( $mag = $config->{$oid} ) {
	    $source = $mag->{source};
	    $mag = $mag->{mag};
	}
	$handler->( {
		id	=> $oid,
		name	=> $name,
		mag	=> $mag,
		source	=> $source,
	    }
	);
    }
    return;
}

sub process_perl {
    my ( @arg ) = @_;
    process_parse( \&print_perl, @arg );
    return;
}

1;

__END__

=head1 TITLE

heavens-above-mag - Get magnitudes from Heavens Above

=head1 SYNOPSIS

 heavens-above-mag 25544
 heavens-above-mag --help
 heavens-above-mag --version

=head1 OPTIONS

=head2 --age

 --age 43200

This option specifies the maximum age of the cache, in seconds. Setting
C<--age=0> disables the cache.

The default is C<--age=86400>, i.e. one day.

=head2 --celestrak

If this Boolean option is asserted, the OIDs come from Celestrak's
F<visual.txt> file, and the output is the canned magnitude table in
L<Astro::Coord::ECI::TLE|Astro::Coord::ECI::TLE>. If this option is
asserted, no non-option arguments may be specified, and
L<--open|/--open> is ignored.

The default is the value of L<--update|/--update>.

=head2 --clear

This option causes the cache to be cleared before any magnitudes are
retrieved. The script will exit afterwards unless either arguments or
L<--celestrak|/--celestrak> were specified.

If more than one of C<--clear>, L<--purge|/--purge>, or
L<--touch|/--touch> is specified, the last-specified wins.

=head2 --config

This option specifies the location of a magnitude configuration file.
The default is F<mets/magnituderc>. See L<CONFIGURATION|/CONFIGURATION>
below for more.

The default configuration file need not exist, but an
explicitly-specified configuration file must exist.

=head2 --delay

This option specifies the number of seconds between web fetches.

The default is C<--delay 5>.

=head2 --help

This option displays the documentation for this script. The script then
exits.

=head2 --open

If this Boolean option is asserted, a web browser is spawned, displaying
the Heavens-Above web page of the OIDs specified. You cannot specify
file names if you specify this option.

=head2 --purge

This option causes the cache to be purged before any magnitudes are
retrieved. The script will exit afterwards unless either arguments or
L<--celestrak|/--celestrak> were specified.

If more than one of L<--clear|/--clear>, C<--purge>, or
L<--touch|/--touch> is specified, the last-specified wins.

=head2 --touch

This option causes the creation time of all objects in the cache to be
reset to the current time before any magnitudes are retrieved. The
script will exit afterwards unless either arguments or
L<--celestrak|/--celestrak> were specified.

If more than one of L<--clear|/--clear>, L<--purge|/--purge>, or
C<--touch> is specified, the last-specified wins.

=head2 --update

This option causes everything between the lines

 # $$ BEGIN magnitude_table

and

 # $$ END

in F<lib/Astro/Coord/ECI/TLE.pm> to be replaced by the output
of the L<--celestrak|/--celestrak> option. An error is reported if the
file can not be opened, or if the markers are not found.

The default is C<--no-update>.

=head2 --user-agent

 --user-agent Wget/1.25.0

This option specifies the user agent string for web queries. The default
is the default L<LWP::UserAgent|LWP::UserAgent> string.

=head2 --verbose

If this Boolean option is asserted, whatever information the author
deems useful is displayed on C<STDERR>.

The default is C<--no-verbose>.

=head2 --version

This option displays the version of this script. The script then exits.

=head1 DETAILS

This Perl script parses intrinsic magnitude data out of Heavens Above
data. You can specify either an OID (which is fetched) or a file name
(which is read) or a mixture of the two.

Heavens Above defines intrinsic magnitude as the magnitude at a range of
1000km, and 50% illuminated.

All web I/O goes through a cache in top-level project directory
F<cache/>. Data will come from the cache rather than the web if the file
in the cache is newer than the value of the L<--age|/--age> option. The
cache directory will be created if necessary.

=head1 CONFIGURATION

Besides scraping Heavens Above, magnitudes can come from a configuration
file. By default this is L<meta/magnituderc>, but a different one can be
specified using the L<--config|/--config> option.

The configuration file allows comments beginning with C<#>, either
full-line or end-of-line. These are stripped. Any line containing no
non-white-space characters after this operation is ignored.

Configuration lines are of the form C<name = value>. The following names
are allowed:

=over

=item * An unsigned integer

This is interpreted as an OID. The value is the default magnitude for
that object, assuming one can not be obtained from Heavens Above.

=item * C<age>

This specifies a value for the L<--age|/--age> option. The value must be
an unsigned integer number of seconds.

=item * C<delay>

This specifies a value for the L<--delay|/--delay> option. The value
must be an unsigned integer number of seconds.

=item * C<source>

This specifies the name of the source for all subsequent magnitudes
until the next C<source> specification. The default is the name of the
configuration file.

=item * C<user_agent>

This specifies the user agent string for all web requests. The default
is the default L<LWP::UserAgent|LWP::UserAgent> string.

=back

=head1 AUTHOR

Thomas R. Wyant, III F<harryfmudd at comcast dot net>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2021-2026 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the Artistic
License 1.0 at
L<https://www.perlfoundation.org/artistic-license-10.html>, and/or the
Gnu GPL at L<http://www.gnu.org/licenses/old-licenses/gpl-1.0.txt>.

This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut

# ex: set textwidth=72 :
