package EPrints::KlarasConnect::Tick;

# The scheduled run: started by the panel every 15 minutes (signed tick)
# and by the indexer cron event as a fallback. Every step is idempotent
# and guarded by a database lock, so the two can overlap safely.
#
# Heavy work (the health scan, the discover cache) is handed to the
# indexer; a tick only ever does quick things, so the panel's request
# returns in well under a second.

use strict;
use warnings;

use POSIX ();
use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Identity;
use EPrints::KlarasConnect::Licence;
use EPrints::KlarasConnect::PanelClient;
use EPrints::KlarasConnect::Schema;
use EPrints::KlarasConnect::Settings;
use EPrints::KlarasConnect::UsageLog;

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

	my $lock = _lock( $repo );
	return { ran => \0, state => 'busy' } if !$lock;

	my %out = ( ran => \1 );
	my $ok = eval {
		EPrints::KlarasConnect::Settings::set( $repo, last_tick_at => time );

		if( EPrints::KlarasConnect::Settings::is_activated( $repo )
			&& ( $opts{refresh} || EPrints::KlarasConnect::Licence::due( $repo ) ) )
		{
			my $hb = heartbeat( $repo );
			$out{heartbeat} = $hb->{ok} ? 'ok' : $hb->{error}->{code};
		}

		heal_queue( $repo );
		_queue_background( $repo );
		1;
	};
	if( !$ok )
	{
		$repo->log( "klaras_connect: tick failed: $@" );
		$out{state} = 'error';
	}
	_unlock( $repo );

	$out{state} ||= EPrints::KlarasConnect::Licence::state( $repo );
	return \%out;
}

# Reports to the panel and stores its licence verdict.
sub heartbeat
{
	my( $repo ) = @_;

	my $payload = EPrints::KlarasConnect::Identity::report( $repo );
	$payload->{metrics} = metrics( $repo );

	my $res = EPrints::KlarasConnect::PanelClient::post( $repo, '/api/v1/instances/heartbeat', $payload,
		api_key => EPrints::KlarasConnect::Settings::get( $repo, 'api_key', fresh => 1 ) );

	if( $res->{ok} )
	{
		EPrints::KlarasConnect::Licence::remember( $repo, $res->{data} );
		EPrints::KlarasConnect::Settings::set( $repo, last_heartbeat_at => time, last_heartbeat_error => undef );
	}
	else
	{
		# A key the panel no longer knows: stop member access now rather than
		# waiting for the grace period.
		if( $res->{status} == 401 || $res->{status} == 403 )
		{
			my $stored = EPrints::KlarasConnect::Licence::stored( $repo ) || {};
			$stored->{instance_status} = 'revoked';
			$stored->{verdict} ||= { valid => 0, features => {} };
			EPrints::KlarasConnect::Settings::set_json( $repo, 'licence', $stored );
		}
		EPrints::KlarasConnect::Settings::set( $repo,
			last_heartbeat_error => substr( $res->{error}->{message} || $res->{error}->{code}, 0, 300 ) );
	}
	return $res;
}

# Counts only: no names, nothing a member typed.
sub metrics
{
	my( $repo ) = @_;

	my %m = ( last_cron_at => _iso( EPrints::KlarasConnect::Settings::get( $repo, 'last_tick_at' ) ) );

	require EPrints::KlarasConnect::Health;
	my $snap = EPrints::KlarasConnect::Health::latest( $repo );
	if( ref $snap eq 'HASH' && ref $snap->{profile} eq 'HASH' )
	{
		$m{repository} = { %{ $snap->{profile} }, health_score => $snap->{score}, health_day => $snap->{day} };
	}

	my $usage = EPrints::KlarasConnect::UsageLog::summary( $repo );
	$m{usage} = $usage if ref $usage eq 'HASH';

	# Public metadata of the most-read records (titles are already public
	# on the repository's own pages).
	my @top;
	foreach my $r ( @{ EPrints::KlarasConnect::UsageLog::top_records( $repo, 30, 10 ) } )
	{
		require EPrints::KlarasConnect::Records;
		my $e = EPrints::KlarasConnect::Records::live_eprint( $repo, $r->{eprintid} ) or next;
		my $title = eval { $e->value( 'title' ) };
		push @top, {
			id        => '' . $e->id,
			title     => defined $title ? substr( $title, 0, 300 ) : undef,
			downloads => ( $r->{downloads} || 0 ) + 0,
			views     => ( $r->{views} || 0 ) + 0,
			readers   => ( $r->{readers} || 0 ) + 0,
		};
	}
	$m{top_records_30d} = \@top;

	return \%m;
}

# Queues the indexer jobs that are due. create_unique makes a repeat a no-op.
sub _queue_background
{
	my( $repo ) = @_;

	my $day = POSIX::strftime( '%Y-%m-%d', gmtime );
	my @jobs;

	require EPrints::KlarasConnect::Health;
	my $latest = EPrints::KlarasConnect::Health::latest( $repo );
	push @jobs, 'health' if ref $latest ne 'HASH' || $latest->{day} ne $day;

	my $at = EPrints::KlarasConnect::Settings::get( $repo, 'discover_cached_at' ) || 0;
	push @jobs, 'discover' if time - $at > 3600;

	ensure_schedule( $repo );

	foreach my $action ( @jobs, 'housekeeping' )
	{
		eval {
			EPrints::DataObj::EventQueue->create_unique( $repo, {
				pluginid => 'Event::KlarasConnect',
				action   => $action,
				params   => [],
			} );
			1;
		} or $repo->log( "klaras_connect: could not queue $action: $@" );
	}
}

# The indexer's own 15-minute schedule, for repositories the panel cannot
# reach. EPrints' built-in Event::cron re-queues itself; create_unique
# makes calling this again a no-op.
sub ensure_schedule
{
	my( $repo ) = @_;
	my $ok = eval {
		EPrints::DataObj::EventQueue->create_unique( $repo, {
			pluginid => 'Event',
			action   => 'cron',
			params   => [ '7,22,37,52 * * * *', 'Event::KlarasConnect', 'tick' ],
		} );
		1;
	};
	$repo->log( "klaras_connect: could not schedule the indexer tick: $@" ) if !$ok;
	return $ok ? 1 : 0;
}

# A job left 'inprogress' this long after its start time was cut off (the
# indexer was stopped, or its alarm fired) and will never finish.
use constant STALE_SECONDS => 6 * 3600;

# Puts back in the queue the Klaras jobs the indexer would never run again:
#
# - 'failed' ones. 3.4's create_unique resets them, but 3.3's cannot
#   replace them (same id), so a single failure, e.g. a job queued before
#   the indexer had loaded the plugin, would stop that job for good;
# - 'inprogress' ones whose run was cut off. EPrints never recovers them.
#
# Cheap (one indexed select on a small table) and idempotent. Called by
# every tick, so the panel's tick heals the indexer's cron and the
# indexer's tick heals the rest; Handler calls it at most hourly for
# repositories that neither reaches.
sub heal_queue
{
	my( $repo ) = @_;
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo ) or return 0;
	my $ids = eval {
		$dbh->selectcol_arrayref(
			'SELECT eventqueueid FROM event_queue WHERE status IN (?, ?) AND (pluginid = ? OR (pluginid = ? AND action = ?))',
			undef, 'failed', 'inprogress', 'Event::KlarasConnect', 'Event', 'cron' );
	} || [];
	return 0 if !@$ids;

	my $stale = POSIX::strftime( '%Y-%m-%d %H:%M:%S', gmtime( time - STALE_SECONDS ) );
	my $ds = $repo->dataset( 'event_queue' );
	my $healed = 0;
	foreach my $id ( @$ids )
	{
		my $ev = eval { $ds->dataobj( $id ) } or next;
		# Of the core cron entries, only ours.
		next if $ev->value( 'pluginid' ) eq 'Event' && !_is_our_cron( $ev );
		my $status = $ev->value( 'status' ) || '';
		my $start = $ev->value( 'start_time' ) || '';
		next if $status eq 'inprogress' && $start gt $stale;
		my $ok = eval { $ev->set_value( 'status', 'waiting' ); $ev->commit; 1 };
		$healed++ if $ok;
	}
	$repo->log( "klaras_connect: put $healed stopped indexer job(s) back in the queue" ) if $healed;
	return $healed;
}

sub _is_our_cron
{
	my( $ev ) = @_;
	my $params = $ev->value( 'params' );
	return ref $params eq 'ARRAY' && defined $params->[1] && $params->[1] eq 'Event::KlarasConnect' ? 1 : 0;
}

# On disable/uninstall: the indexer must not keep calling a plugin that is
# gone. Removes the cron entry and any queued one-off Klaras jobs.
sub remove_schedule
{
	my( $repo ) = @_;
	my $removed = 0;
	eval {
		my $cron = EPrints::DataObj::EventQueue->new_from_hash( $repo, {
			pluginid => 'Event',
			action   => 'cron',
			params   => [ '7,22,37,52 * * * *', 'Event::KlarasConnect', 'tick' ],
		} );
		if( defined $cron ) { $cron->remove; $removed++ }
		1;
	} or $repo->log( "klaras_connect: could not remove the indexer tick: $@" );

	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo );
	my $ids = $dbh ? eval {
		$dbh->selectcol_arrayref( 'SELECT eventqueueid FROM event_queue WHERE pluginid = ?', undef, 'Event::KlarasConnect' );
	} : undef;
	my $ds = $repo->dataset( 'event_queue' );
	foreach my $id ( @{ $ids || [] } )
	{
		my $ev = eval { $ds->dataobj( $id ) } or next;
		$removed++ if eval { $ev->remove; 1 };
	}
	return $removed;
}

sub _lock
{
	my( $repo ) = @_;
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo ) or return 0;
	my( $got ) = eval { $dbh->selectrow_array( 'SELECT GET_LOCK(?, 0)', undef, 'klaras_connect_tick_' . $repo->get_id ) };
	return $got ? 1 : 0;
}

sub _unlock
{
	my( $repo ) = @_;
	my $dbh = EPrints::KlarasConnect::Schema::dbh( $repo ) or return;
	eval { $dbh->selectrow_array( 'SELECT RELEASE_LOCK(?)', undef, 'klaras_connect_tick_' . $repo->get_id ) };
}

sub _iso
{
	my( $t ) = @_;
	return $t ? POSIX::strftime( '%Y-%m-%dT%H:%M:%SZ', gmtime $t ) : undef;
}

1;
