package EPrints::KlarasConnect::Telemetry;

# Anonymous weekly profile for repositories that have NOT connected an API
# key (connected ones report through the heartbeat instead). Opt-in: off
# until the librarian switches it on in Klaras Connect settings, and an
# opt-out is sent once when they switch it off again.
#
# Counts only, from the latest health report, plus the repository's
# public name and address. No record titles, nothing about any person.
#
# Endpoint (shared with Klaras Inven): POST /api/v1/telemetry/plugins/eprints-connect
# The stats keys are a contract with the panel's per-plugin key list
# (PluginTelemetryRequest): add, never rename.

use strict;
use warnings;

use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Compat;
use EPrints::KlarasConnect::Identity;
use EPrints::KlarasConnect::PanelClient;
use EPrints::KlarasConnect::Settings;
use EPrints::KlarasConnect::Util qw( uuid_v4 is_uuid );

use constant PLUGIN   => 'eprints-connect';
use constant INTERVAL => 7 * 86400;

our @STATS = qw(
	records_archived records_with_files records_open documents
	docs_public docs_validuser docs_staffonly embargo_overdue
	deposits_30d buffer_pending duplicate_titles zero_byte_files
	health_score
);

sub install_id
{
	my( $repo ) = @_;
	my $id = EPrints::KlarasConnect::Settings::get( $repo, 'install_id', fresh => 1 );
	return $id if is_uuid( $id );
	$id = uuid_v4();
	EPrints::KlarasConnect::Settings::set( $repo, install_id => $id );
	return $id;
}

# Pure: the payload from a health report.
sub payload
{
	my( %p ) = @_;
	my $profile = ref $p{report} eq 'HASH' && ref $p{report}->{profile} eq 'HASH' ? $p{report}->{profile} : {};
	my %stats;
	foreach my $k ( @STATS )
	{
		my $v = $k eq 'health_score' ? ( ref $p{report} eq 'HASH' ? $p{report}->{score} : undef ) : $profile->{$k};
		$stats{$k} = $v + 0 if defined $v && !ref $v && $v =~ /\A[0-9]{1,10}\z/;
	}
	return {
		install_id  => $p{install_id},
		library     => { name => $p{name}, site_url => $p{site_url} },
		environment => {
			plugin_version   => $p{plugin_version},
			platform_version => $p{platform_version},
		},
		stats => \%stats,
	};
}

sub send_if_due
{
	my( $repo, %opts ) = @_;

	# Connected repositories report through the heartbeat.
	return 0 if EPrints::KlarasConnect::Settings::is_activated( $repo );
	return 0 if !EPrints::KlarasConnect::Settings::get( $repo, 'telemetry_opt_in' );

	my $last = EPrints::KlarasConnect::Settings::get( $repo, 'last_telemetry_at' ) || 0;
	return 0 if !$opts{force} && time - $last < INTERVAL;

	require EPrints::KlarasConnect::Health;
	my $body = payload(
		install_id       => install_id( $repo ),
		name             => EPrints::KlarasConnect::Identity::display_name( $repo ),
		site_url         => EPrints::KlarasConnect::Identity::base_url( $repo ),
		plugin_version   => EPrints::KlarasConnect::version(),
		platform_version => EPrints::KlarasConnect::Compat::eprints_version(),
		report           => EPrints::KlarasConnect::Health::latest( $repo ),
	);

	my $res = EPrints::KlarasConnect::PanelClient::post( $repo, '/api/v1/telemetry/plugins/' . PLUGIN, $body );
	EPrints::KlarasConnect::Settings::set( $repo, last_telemetry_at => time ) if $res->{ok};
	return $res->{ok} ? 1 : 0;
}

# Called when the librarian switches sharing off: tell the panel once so it
# can stop listing this installation.
sub send_opt_out
{
	my( $repo ) = @_;
	my $res = EPrints::KlarasConnect::PanelClient::post( $repo, '/api/v1/telemetry/plugins/' . PLUGIN,
		{ install_id => install_id( $repo ), opted_out => \1 } );
	return $res->{ok} ? 1 : 0;
}

1;
