package EPrints::KlarasConnect::Health;

# Laporan Kesehatan Repositori: free, local, no API key needed.
#
# snapshot() runs in the indexer once a day: aggregate SQL on EPrints'
# own tables (never a full object scan), a small sample of files, and a
# fetch of one public abstract page and the OAI-PMH endpoint. The result
# is stored in klaras_connect_health; the screen only reads it.
#
# Every check returns:
#   { key, title, status => good|warn|bad|info, value, detail, fix, weight }
# and a check that cannot run on this schema is skipped, never an error.

use strict;
use warnings;

use POSIX ();
use EPrints::KlarasConnect;
use EPrints::KlarasConnect::Compat;
use EPrints::KlarasConnect::Identity;
use EPrints::KlarasConnect::Schema;
use EPrints::KlarasConnect::Settings;
use EPrints::KlarasConnect::Util qw( json_encode json_decode );

use constant KEEP_DAYS   => 400;
use constant FILE_SAMPLE => 200;

# Pure: 0..100 from checks that carry a ratio and a weight.
sub score
{
	my( $checks ) = @_;
	my( $sum, $w ) = ( 0, 0 );
	foreach my $c ( @$checks )
	{
		next if !defined $c->{ratio} || !$c->{weight};
		my $r = $c->{ratio} < 0 ? 0 : $c->{ratio} > 1 ? 1 : $c->{ratio};
		$sum += $r * $c->{weight};
		$w += $c->{weight};
	}
	return $w ? int( 100 * $sum / $w + 0.5 ) : undef;
}

# Pure: status for a ratio against two thresholds.
sub grade
{
	my( $ratio, $good, $warn ) = @_;
	return 'info' if !defined $ratio;
	return 'good' if $ratio >= $good;
	return 'warn' if $ratio >= $warn;
	return 'bad';
}

sub pct
{
	my( $n, $d ) = @_;
	return undef if !$d;
	return $n / $d;
}

sub _fmt_pct
{
	my( $r ) = @_;
	return defined $r ? sprintf( '%d%%', int( $r * 100 + 0.5 ) ) : '-';
}

# ------------------------------------------------------------------ SQL

sub _dbh { return EPrints::KlarasConnect::Schema::dbh( $_[0] ) }

sub _val
{
	my( $repo, $sql, @bind ) = @_;
	my $dbh = _dbh( $repo ) or return undef;
	my( $v ) = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectrow_array( $sql, undef, @bind );
	};
	return $v;
}

sub _rows
{
	my( $repo, $sql, @bind ) = @_;
	my $dbh = _dbh( $repo ) or return [];
	my $rows = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectall_arrayref( $sql, undef, @bind );
	};
	return $rows || [];
}

sub _rows_or_undef
{
	my( $repo, $sql, @bind ) = @_;
	my $dbh = _dbh( $repo ) or return undef;
	return eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectall_arrayref( $sql, undef, @bind );
	};
}

my %COLS;
sub _has
{
	my( $repo, $table, $col ) = @_;
	my $k = join '|', $repo->get_id, $table, $col;
	return $COLS{$k} if exists $COLS{$k};
	my $db = $repo->get_database;
	my $has = defined $col
		? eval { $db->has_column( $table, $col ) }
		: eval { $db->has_table( $table ) };
	return $COLS{$k} = $has ? 1 : 0;
}

# Documents that are real attachments (not thumbnails / index caches).
sub _real_docs_sql
{
	my( $repo ) = @_;
	if( _has( $repo, 'document_relation_type', 'relation_type' ) )
	{
		return "SELECT d.docid, d.eprintid, d.security FROM document d "
			. "WHERE NOT EXISTS (SELECT 1 FROM document_relation_type r WHERE r.docid = d.docid AND r.relation_type LIKE '%isVolatileVersionOf')";
	}
	return "SELECT d.docid, d.eprintid, d.security FROM document d";
}

# ------------------------------------------------------------------ checks

sub collect
{
	my( $repo ) = @_;

	my $today = POSIX::strftime( '%Y-%m-%d', gmtime );
	my( $ty, $tm, $td ) = split /-/, $today;
	my %profile;
	my @checks;

	my $archived = _val( $repo, "SELECT COUNT(*) FROM eprint WHERE eprint_status = 'archive'" ) || 0;
	$profile{records_archived} = $archived + 0;

	# 1. Metadata completeness.
	my @meta = (
		[ abstract  => 'Abstrak',  "SELECT COUNT(*) FROM eprint WHERE eprint_status = 'archive' AND abstract IS NOT NULL AND abstract <> ''", [ 'eprint', 'abstract' ] ],
		[ keywords  => 'Kata kunci', "SELECT COUNT(*) FROM eprint WHERE eprint_status = 'archive' AND keywords IS NOT NULL AND keywords <> ''", [ 'eprint', 'keywords' ] ],
		[ subjects  => 'Subjek', "SELECT COUNT(DISTINCT s.eprintid) FROM eprint_subjects s JOIN eprint e ON e.eprintid = s.eprintid WHERE e.eprint_status = 'archive'", [ 'eprint_subjects', 'subjects' ] ],
		[ divisions => 'Program studi / unit', "SELECT COUNT(DISTINCT s.eprintid) FROM eprint_divisions s JOIN eprint e ON e.eprintid = s.eprintid WHERE e.eprint_status = 'archive'", [ 'eprint_divisions', 'divisions' ] ],
		[ date      => 'Tahun terbit', "SELECT COUNT(*) FROM eprint WHERE eprint_status = 'archive' AND date_year IS NOT NULL", [ 'eprint', 'date_year' ] ],
	);
	my @meta_parts;
	foreach my $m ( @meta )
	{
		my( $key, $label, $sql, $col ) = @$m;
		next if !_has( $repo, @$col );
		my $n = _val( $repo, $sql );
		next if !defined $n;
		my $r = pct( $n, $archived );
		$profile{"meta_${key}_pct"} = defined $r ? int( $r * 100 + 0.5 ) : undef;
		push @meta_parts, { label => $label, ratio => $r, missing => $archived - $n };
	}
	if( @meta_parts )
	{
		my $avg = 0; $avg += ( $_->{ratio} || 0 ) for @meta_parts; $avg /= @meta_parts;
		my @worst = sort { ( $a->{ratio} || 0 ) <=> ( $b->{ratio} || 0 ) } @meta_parts;
		push @checks, {
			key => 'metadata', title => 'Kelengkapan metadata', weight => 3, ratio => $avg,
			status => grade( $avg, 0.9, 0.7 ), value => _fmt_pct( $avg ),
			detail => join( '; ', map { "$_->{label} " . _fmt_pct( $_->{ratio} ) } @meta_parts ),
			fix => $worst[0]->{missing} > 0
				? "Paling banyak kosong: $worst[0]->{label} ($worst[0]->{missing} karya). Lengkapi lewat Manage Records, atau minta prodi melengkapinya saat setor. Metadata lengkap membuat karya lebih mudah ditemukan Google Scholar dan Garuda."
				: undef,
		};
	}

	# 2-3. Full text and open access.
	my $docs_sql = _real_docs_sql( $repo );
	my $with_files = _val( $repo, "SELECT COUNT(DISTINCT x.eprintid) FROM ($docs_sql) x JOIN eprint e ON e.eprintid = x.eprintid WHERE e.eprint_status = 'archive'" );
	if( defined $with_files )
	{
		$profile{records_with_files} = $with_files + 0;
		my $r = pct( $with_files, $archived );
		push @checks, {
			key => 'fulltext', title => 'Karya dengan teks lengkap', weight => 3, ratio => $r,
			status => grade( $r, 0.85, 0.6 ), value => _fmt_pct( $r ),
			detail => sprintf( '%d dari %d karya punya berkas.', $with_files, $archived ),
			fix => ( defined $r && $r < 0.85 ) ? sprintf( '%d karya belum punya berkas. Unggah teks lengkapnya (boleh dibatasi untuk anggota) agar bisa dibaca dan dikutip.', $archived - $with_files ) : undef,
		};
	}

	my $sec = _rows( $repo, "SELECT x.security, COUNT(*) FROM ($docs_sql) x JOIN eprint e ON e.eprintid = x.eprintid WHERE e.eprint_status = 'archive' GROUP BY x.security" );
	if( @$sec )
	{
		my %s = map { ( defined $_->[0] ? $_->[0] : '' ) => $_->[1] } @$sec;
		my $total = 0; $total += $_ for values %s;
		$profile{documents} = $total;
		$profile{docs_public} = ( $s{public} || 0 ) + 0;
		$profile{docs_validuser} = ( $s{validuser} || 0 ) + 0;
		$profile{docs_staffonly} = ( $s{staffonly} || 0 ) + 0;
		my $open_records = _val( $repo, "SELECT COUNT(DISTINCT x.eprintid) FROM ($docs_sql) x JOIN eprint e ON e.eprintid = x.eprintid WHERE e.eprint_status = 'archive' AND x.security = 'public'" ) || 0;
		$profile{records_open} = $open_records + 0;
		my $r = pct( $open_records, $archived );
		push @checks, {
			key => 'open_access', title => 'Akses terbuka', weight => 2, ratio => $r,
			status => grade( $r, 0.6, 0.3 ), value => _fmt_pct( $r ),
			detail => sprintf( 'Berkas publik %d, khusus anggota %d, khusus petugas %d.', $profile{docs_public}, $profile{docs_validuser}, $profile{docs_staffonly} ),
			fix => $profile{docs_staffonly} > 0
				? 'Berkas "staff only" tidak bisa dibuka siapa pun selain petugas, termasuk anggota di aplikasi. Pertimbangkan mengubahnya ke "registered users only" bila kebijakan kampus mengizinkan.'
				: undef,
		};
	}

	# 4. Embargoes that should have ended.
	if( _has( $repo, 'document', 'date_embargo_year' ) )
	{
		my $over = _val( $repo,
			"SELECT COUNT(*) FROM document WHERE date_embargo_year IS NOT NULL AND security <> 'public' AND "
			. "(date_embargo_year < ? OR (date_embargo_year = ? AND COALESCE(date_embargo_month, 12) < ?) "
			. "OR (date_embargo_year = ? AND COALESCE(date_embargo_month, 12) = ? AND COALESCE(date_embargo_day, 31) < ?))",
			$ty, $ty, $tm, $ty, $tm, $td ) || 0;
		my $active = _val( $repo, "SELECT COUNT(*) FROM document WHERE date_embargo_year IS NOT NULL AND security <> 'public'" ) || 0;
		$profile{embargo_overdue} = $over + 0;
		$profile{embargo_active} = ( $active - $over ) + 0;
		push @checks, {
			key => 'embargo', title => 'Embargo yang sudah lewat', weight => 1, ratio => $over ? 0 : 1,
			status => $over ? 'bad' : 'good', value => $over,
			detail => $over ? "$over berkas masa embargonya sudah habis tetapi masih tertutup." : 'Tidak ada embargo yang tertunda.',
			fix => $over ? 'Jalankan bin/lift_embargos setiap hari lewat cron server, misalnya: 0 1 * * * /opt/eprints3/bin/lift_embargos ' . $repo->get_id : undef,
		};
	}

	# 5. Broken files.
	my $zero = _val( $repo, "SELECT COUNT(*) FROM file f JOIN document d ON d.docid = f.objectid AND f.datasetid = 'document' WHERE f.filesize = 0" );
	my $nomain = _val( $repo, "SELECT COUNT(*) FROM ($docs_sql) x JOIN document d ON d.docid = x.docid LEFT JOIN file f ON f.datasetid = 'document' AND f.objectid = d.docid AND f.filename = d.main WHERE d.main IS NOT NULL AND f.fileid IS NULL" );
	my $missing = _sample_unreadable( $repo );
	if( defined $zero || defined $nomain || defined $missing )
	{
		$profile{zero_byte_files} = ( $zero || 0 ) + 0;
		$profile{missing_main} = ( $nomain || 0 ) + 0;
		$profile{unreadable_sample} = defined $missing ? $missing->{bad} + 0 : undef;
		my $bad = ( $zero || 0 ) + ( $nomain || 0 ) + ( $missing ? $missing->{bad} : 0 );
		push @checks, {
			key => 'files', title => 'Berkas rusak atau hilang', weight => 2, ratio => $bad ? 0.5 : 1,
			status => $bad ? 'bad' : 'good', value => $bad,
			detail => sprintf( '%d berkas 0 byte, %d dokumen tanpa berkas utama%s.', $zero || 0, $nomain || 0,
				$missing ? sprintf( ', %d dari %d sampel tidak bisa dibaca dari disk', $missing->{bad}, $missing->{checked} ) : '' ),
			fix => $bad ? 'Unggah ulang berkas yang rusak dari Manage Records. Berkas yang hilang dari disk biasanya karena pemindahan server tanpa folder documents/.' : undef,
		};
	}

	# 6. Formats.
	if( _has( $repo, 'file', 'mime_type' ) )
	{
		my $fmt = _rows( $repo, "SELECT f.mime_type, COUNT(*) FROM ($docs_sql) x JOIN eprint e ON e.eprintid = x.eprintid JOIN document d ON d.docid = x.docid "
			. "JOIN file f ON f.datasetid = 'document' AND f.objectid = d.docid AND f.filename = d.main WHERE e.eprint_status = 'archive' GROUP BY f.mime_type" );
		my( $pdf, $all ) = ( 0, 0 );
		foreach( @$fmt ) { $all += $_->[1]; $pdf += $_->[1] if defined $_->[0] && $_->[0] eq 'application/pdf' }
		if( $all )
		{
			my $r = pct( $pdf, $all );
			$profile{docs_pdf_pct} = int( $r * 100 + 0.5 );
			push @checks, {
				key => 'formats', title => 'Berkas PDF', weight => 1, ratio => $r,
				status => grade( $r, 0.8, 0.5 ), value => _fmt_pct( $r ),
				detail => "$pdf dari $all berkas utama berformat PDF.",
				fix => $r < 0.8 ? 'Berkas Word atau gambar sulit dibaca di ponsel dan tidak diindeks teksnya. Simpan versi PDF sebagai berkas utama.' : undef,
			};
		}
	}

	# 7-8. Discoverability (Google Scholar meta tags, OAI-PMH).
	my $seo = _discoverability( $repo );
	if( $seo )
	{
		$profile{scholar_meta_ok} = $seo->{meta} ? \1 : \0;
		$profile{oai_ok} = $seo->{oai} ? \1 : \0;
		push @checks, {
			key => 'scholar', title => 'Siap diindeks Google Scholar', weight => 3, ratio => $seo->{meta} ? ( $seo->{pdf} ? 1 : 0.6 ) : 0,
			status => $seo->{meta} ? ( $seo->{pdf} ? 'good' : 'warn' ) : ( defined $seo->{meta} ? 'bad' : 'info' ),
			value => defined $seo->{meta} ? ( $seo->{meta} ? 'Ya' : 'Tidak' ) : 'Tidak diketahui',
			detail => $seo->{detail_meta},
			fix => !$seo->{meta}
				? 'Halaman abstrak belum memuat meta citation_* atau eprints.*. Pastikan template halaman ringkasan memuat <epc:pin ref="head"/>; di EPrints 3.4 aktifkan juga plugin Export::HighwirePress.'
				: !$seo->{pdf} ? 'Tambahkan meta citation_pdf_url agar Google Scholar menautkan teks lengkap.' : undef,
		};
		push @checks, {
			key => 'oai', title => 'OAI-PMH (Garuda, BASE, Google)', weight => 2, ratio => defined $seo->{oai} ? ( $seo->{oai} ? 1 : 0 ) : undef,
			status => defined $seo->{oai} ? ( $seo->{oai} ? 'good' : 'bad' ) : 'info',
			value => defined $seo->{oai} ? ( $seo->{oai} ? 'Aktif' : 'Bermasalah' ) : 'Tidak diketahui',
			detail => $seo->{detail_oai},
			fix => defined $seo->{oai} && !$seo->{oai} ? 'Periksa /cgi/oai2?verb=Identify di peramban. Garuda dan BASE memanen lewat OAI-PMH; jika gagal, karya tidak muncul di sana.' : undef,
		};
	}

	# 9. Deposits.
	if( _has( $repo, 'eprint', 'datestamp_year' ) )
	{
		my $rows = _rows( $repo,
			"SELECT datestamp_year, datestamp_month, COUNT(*) FROM eprint WHERE eprint_status = 'archive' AND datestamp_year IS NOT NULL "
			. "GROUP BY datestamp_year, datestamp_month ORDER BY datestamp_year DESC, datestamp_month DESC LIMIT 24" );
		my @trend = reverse map { { month => sprintf( '%04d-%02d', $_->[0], $_->[1] || 0 ), count => $_->[2] + 0 } } @$rows;
		$profile{deposits_by_month} = \@trend;
		my $since = POSIX::strftime( '%Y-%m-%d', gmtime( time - 30 * 86400 ) );
		my( $sy, $sm, $sd ) = split /-/, $since;
		$profile{deposits_30d} = ( _val( $repo,
			"SELECT COUNT(*) FROM eprint WHERE eprint_status = 'archive' AND (datestamp_year > ? OR (datestamp_year = ? AND datestamp_month > ?) OR (datestamp_year = ? AND datestamp_month = ? AND datestamp_day >= ?))",
			$sy, $sy, $sm, $sy, $sm, $sd ) || 0 ) + 0;

		if( _has( $repo, 'eprint_divisions', 'divisions' ) )
		{
			my $cut = POSIX::strftime( '%Y%m', gmtime( time - 182 * 86400 ) );
			my $quiet = _rows( $repo,
				"SELECT d.divisions, MAX(e.datestamp_year * 100 + e.datestamp_month) AS lastdep FROM eprint_divisions d JOIN eprint e ON e.eprintid = d.eprintid "
				. "WHERE e.eprint_status = 'archive' GROUP BY d.divisions HAVING lastdep < ? ORDER BY lastdep LIMIT 20", $cut );
			$profile{quiet_divisions} = scalar @$quiet;
			require EPrints::KlarasConnect::Records;
			push @checks, {
				key => 'deposits', title => 'Setoran 6 bulan terakhir', weight => 1,
				ratio => undef, status => @$quiet ? 'warn' : 'good',
				value => $profile{deposits_30d} . ' karya / 30 hari',
				detail => @$quiet
					? scalar( @$quiet ) . ' prodi/unit tidak menyetor 6 bulan: ' . join( ', ', map { EPrints::KlarasConnect::Records::subject_label( $repo, $_->[0] ) || $_->[0] } @$quiet[ 0 .. ( $#$quiet < 4 ? $#$quiet : 4 ) ] ) . ( @$quiet > 5 ? ', ...' : '' )
					: 'Semua prodi/unit menyetor dalam 6 bulan terakhir.',
				fix => @$quiet ? 'Kirim pengingat ke prodi tersebut; setoran rutin menjaga repositori tetap hidup di mata pemeringkat (Webometrics, SINTA).' : undef,
			};
		}
	}

	# 10. Review queue.
	my $buffer = _val( $repo, "SELECT COUNT(*) FROM eprint WHERE eprint_status = 'buffer'" );
	if( defined $buffer )
	{
		$profile{buffer_pending} = $buffer + 0;
		my $oldest;
		if( _has( $repo, 'eprint', 'status_changed_year' ) )
		{
			my $row = _rows( $repo, "SELECT status_changed_year, status_changed_month, status_changed_day FROM eprint WHERE eprint_status = 'buffer' AND status_changed_year IS NOT NULL ORDER BY status_changed_year, status_changed_month, status_changed_day LIMIT 1" );
			if( @$row )
			{
				require Time::Local;
				my $t = eval { Time::Local::timegm( 0, 0, 0, $row->[0]->[2] || 1, ( $row->[0]->[1] || 1 ) - 1, $row->[0]->[0] ) };
				$oldest = defined $t ? int( ( time - $t ) / 86400 ) : undef;
			}
		}
		$profile{buffer_oldest_days} = $oldest;
		my $late = defined $oldest && $oldest > 14;
		push @checks, {
			key => 'review', title => 'Antrean review', weight => 1, ratio => $late ? 0.3 : 1,
			status => $late ? 'warn' : 'good', value => $buffer,
			detail => $buffer ? "$buffer karya menunggu review" . ( defined $oldest ? ", yang tertua $oldest hari." : '.' ) : 'Tidak ada antrean.',
			fix => $late ? 'Karya yang terlalu lama di antrean belum bisa dibaca siapa pun. Tinjau di Manage Deposits > Review.' : undef,
		};
	}

	# 11. Duplicates.
	my $dups = _rows_or_undef( $repo,
		"SELECT LOWER(TRIM(title)) AS t, COUNT(*) AS n FROM eprint WHERE eprint_status = 'archive' AND title IS NOT NULL AND title <> '' "
		. "GROUP BY t HAVING n > 1 ORDER BY n DESC LIMIT 50" );
	if( defined $dups )
	{
		my $n = 0; $n += $_->[1] - 1 for @$dups;
		$profile{duplicate_titles} = $n;
		push @checks, {
			key => 'duplicates', title => 'Judul ganda', weight => 1, ratio => pct( $archived - $n, $archived ),
			status => $n ? 'warn' : 'good', value => $n,
			detail => $n ? scalar( @$dups ) . ' judul muncul lebih dari sekali.' : 'Tidak ada judul ganda.',
			fix => $n ? 'Periksa dan gabungkan karya ganda; duplikat membagi jumlah unduhan dan sitasi.' : undef,
		};
	}

	# 12. ORCID (informational: student theses rarely have one, so it does
	# not change the score). ORCID packages add creators_orcid; otherwise
	# campuses often type it into creators_id.
	my( $otable, $ocol ) = _has( $repo, 'eprint_creators_orcid', 'creators_orcid' ) ? ( 'eprint_creators_orcid', 'creators_orcid' )
		: _has( $repo, 'eprint_creators_id', 'creators_id' ) ? ( 'eprint_creators_id', 'creators_id' ) : ();
	if( $otable )
	{
		my $n = _val( $repo,
			"SELECT COUNT(DISTINCT o.eprintid) FROM $otable o JOIN eprint e ON e.eprintid = o.eprintid "
			. "WHERE e.eprint_status = 'archive' AND o.$ocol REGEXP '[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]'" );
		if( defined $n )
		{
			my $r = pct( $n, $archived );
			$profile{records_with_orcid} = $n + 0;
			push @checks, {
				key => 'orcid', title => 'Penulis dengan ORCID', weight => 0, ratio => undef,
				status => 'info', value => _fmt_pct( $r ),
				detail => "$n karya mencantumkan ORCID minimal satu penulis.",
				fix => ( defined $r && $r < 0.3 )
					? 'ORCID menautkan karya dosen ke profil SINTA dan Google Scholar mereka. Isi ORCID pada kolom ID penulis (format 0000-0000-0000-0000), atau pasang paket ORCID dari EPrints Bazaar.'
					: undef,
			};
		}
	}

	# 13. Technical.
	my $base = EPrints::KlarasConnect::Identity::base_url( $repo );
	my @tech;
	push @tech, 'EPrints ' . EPrints::KlarasConnect::Compat::eprints_version();
	push @tech, 'Perl ' . sprintf( '%vd', $^V );
	my $indexer = EPrints::KlarasConnect::Compat::indexer_running( $repo );
	my $https = $base =~ m{\Ahttps://} ? 1 : 0;
	require EPrints::KlarasConnect::PanelClient;
	my $out = defined EPrints::KlarasConnect::PanelClient::transport() ? 1 : 0;
	my $xap = EPrints::KlarasConnect::Compat::has_xapian( $repo );
	my @tech_fix;
	push @tech_fix, 'Jalankan indexer: bin/epindexer start (dan pasang sebagai service).' if !$indexer;
	push @tech_fix, 'Pasang sertifikat HTTPS (misalnya Let\'s Encrypt); aplikasi anggota dan Google memprioritaskan https.' if !$https;
	push @tech_fix, 'Pasang liblwp-protocol-https-perl agar repositori bisa terhubung ke panel Klaras.' if !$out;
	push @checks, {
		key => 'technical', title => 'Kesehatan teknis', weight => 2,
		ratio => ( $indexer + $https + $out ) / 3,
		status => @tech_fix ? ( $indexer ? 'warn' : 'bad' ) : 'good',
		value => @tech_fix ? scalar( @tech_fix ) . ' perlu perhatian' : 'Baik',
		detail => join( ', ', @tech, 'indexer ' . ( $indexer ? 'berjalan' : 'tidak berjalan' ),
			'HTTPS ' . ( $https ? 'ya' : 'tidak' ), 'Xapian ' . ( $xap ? 'ya' : 'tidak' ) ),
		fix => @tech_fix ? join( ' ', @tech_fix ) : undef,
	};
	$profile{https} = $https ? \1 : \0;
	$profile{indexer_running} = $indexer ? \1 : \0;
	$profile{xapian} = $xap ? \1 : \0;
	$profile{eprints_version} = EPrints::KlarasConnect::Compat::eprints_version();

	return { day => $today, score => score( \@checks ), checks => \@checks, profile => \%profile, created_at => time };
}

# Reads one byte of a sample of the newest main files, through EPrints'
# storage layer (works for local disk and storage plugins alike).
sub _sample_unreadable
{
	my( $repo ) = @_;
	my $rows = _rows( $repo,
		"SELECT f.fileid FROM file f JOIN document d ON d.docid = f.objectid AND f.datasetid = 'document' AND f.filename = d.main "
		. "WHERE f.filesize > 0 ORDER BY f.fileid DESC LIMIT " . FILE_SAMPLE );
	return undef if !@$rows;
	my $ds = EPrints::KlarasConnect::Compat::dataset( $repo, 'file' ) or return undef;
	my( $checked, $bad ) = ( 0, 0 );
	my $deadline = time + 60;
	foreach my $r ( @$rows )
	{
		last if time > $deadline;
		my $file = eval { $ds->dataobj( $r->[0] ) } or next;
		$checked++;
		my $got = 0;
		my $ok = eval { $file->get_file( sub { $got += length $_[0]; 0 }, 0, 1 ) };
		$bad++ if !$ok && !$got;
	}
	return { checked => $checked, bad => $bad };
}

sub _discoverability
{
	my( $repo ) = @_;

	my %out = ( meta => undef, pdf => undef, oai => undef,
		detail_meta => 'Belum bisa diperiksa dari server ini.', detail_oai => 'Belum bisa diperiksa dari server ini.' );
	return \%out if !EPrints::KlarasConnect::Compat::has_lwp_https();

	my $base = EPrints::KlarasConnect::Identity::base_url( $repo );
	require LWP::UserAgent;
	my $ua = LWP::UserAgent->new( timeout => 15, max_size => 512 * 1024, max_redirect => 3,
		agent => EPrints::KlarasConnect::USER_AGENT . ' (health check)' );

	# One recent record with a public file.
	my $docs_sql = _real_docs_sql( $repo );
	my( $id ) = map { $_->[0] } @{ _rows( $repo,
		"SELECT x.eprintid FROM ($docs_sql) x JOIN eprint e ON e.eprintid = x.eprintid WHERE e.eprint_status = 'archive' AND x.security = 'public' ORDER BY x.eprintid DESC LIMIT 1" ) };
	if( defined $id )
	{
		require EPrints::KlarasConnect::Records;
		my $e = EPrints::KlarasConnect::Records::live_eprint( $repo, $id );
		my $url = defined $e ? eval { $e->get_url } : undef;
		$url = EPrints::KlarasConnect::Records::_absolute( $base, $url ) if defined $url;
		if( defined $url )
		{
			my $res = eval { $ua->get( $url ) };
			if( $res && $res->is_success )
			{
				my $html = $res->decoded_content || '';
				my $meta = $html =~ /<meta[^>]+name=["'](?:citation_title|eprints\.title)["']/i ? 1 : 0;
				my $pdf = $html =~ /<meta[^>]+name=["'](?:citation_pdf_url|eprints\.document_url)["']/i ? 1 : 0;
				@out{qw( meta pdf )} = ( $meta, $pdf );
				$out{detail_meta} = $meta
					? 'Halaman abstrak memuat meta untuk Google Scholar' . ( $pdf ? ', termasuk tautan PDF.' : ', tetapi tanpa tautan PDF.' )
					: 'Halaman abstrak tidak memuat meta citation_* / eprints.*.';
			}
			elsif( $res )
			{
				$out{detail_meta} = 'Halaman abstrak tidak bisa dibuka dari server ini (HTTP ' . $res->code . ').';
			}
		}
	}

	my $oai = eval { $ua->get( $base . '/cgi/oai2?verb=Identify' ) };
	if( $oai && $oai->is_success && ( $oai->decoded_content || '' ) =~ /<Identify>/ )
	{
		$out{oai} = 1;
		$out{detail_oai} = 'Endpoint OAI-PMH menjawab dengan benar.';
	}
	elsif( $oai )
	{
		$out{oai} = 0;
		$out{detail_oai} = 'Endpoint OAI-PMH tidak menjawab dengan benar (HTTP ' . $oai->code . ').';
	}

	return \%out;
}

# ------------------------------------------------------------------ storage

sub snapshot
{
	my( $repo ) = @_;

	return undef if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $report = collect( $repo );
	my $dbh = _dbh( $repo );
	eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->do( 'REPLACE INTO klaras_connect_health (day, report, created_at) VALUES (?, ?, ?)',
			undef, $report->{day}, json_encode( $report ), time );
		1;
	} or $repo->log( "klaras_connect: could not store health report: $@" );
	return $report;
}

sub latest
{
	my( $repo ) = @_;
	return undef if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = _dbh( $repo );
	my( $json ) = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectrow_array( 'SELECT report FROM klaras_connect_health ORDER BY day DESC LIMIT 1' );
	};
	return defined $json ? json_decode( $json ) : undef;
}

# Score per day for the trend line.
sub history
{
	my( $repo, $days ) = @_;
	return [] if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = _dbh( $repo );
	my $rows = eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->selectall_arrayref( 'SELECT day, report FROM klaras_connect_health ORDER BY day DESC LIMIT ?', undef, $days + 0 );
	} || [];
	my @out;
	foreach my $r ( reverse @$rows )
	{
		my $d = json_decode( $r->[1] ) or next;
		push @out, { day => "$r->[0]", score => $d->{score} };
	}
	return \@out;
}

sub prune
{
	my( $repo ) = @_;
	return if !EPrints::KlarasConnect::Schema::ensure( $repo );
	my $dbh = _dbh( $repo );
	my $cut = POSIX::strftime( '%Y-%m-%d', gmtime( time - KEEP_DAYS * 86400 ) );
	eval {
		local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0;
		$dbh->do( 'DELETE FROM klaras_connect_health WHERE day < ?', undef, $cut );
		1;
	};
}

1;
