package EPrints::KlarasConnect::Search;

# GET /records: search the live archive.
#
# - Xapian when the repository runs it (relevance ranking), otherwise the
#   EPrints internal word index. Both use indexes; nothing here ever
#   scans a table with LIKE.
# - Every filter value is validated before it reaches EPrints; field
#   names come from this file, never from the request.
# - Paging is offset-based and capped, so a deep page can never become an
#   expensive query.

use strict;
use warnings;

use EPrints::KlarasConnect::Compat;

use constant MAX_LIMIT  => 50;
use constant DEF_LIMIT  => 20;
use constant MAX_OFFSET => 1000;
use constant MAX_Q      => 200;

# Xapian only estimates how many documents match, and on small pages the
# estimate can fall well short (6 of 11 on Xapian 1.4.5): a member would be
# told of fewer hits than there are, and paging would stop early. Asking it
# to look at least this far makes the count exact as deep as paging can go,
# without loading a single extra document.
use constant COUNT_EXACT => MAX_OFFSET + MAX_LIMIT;

my %SORTS = (
	relevance => undef,
	latest    => '-datestamp',
	year      => '-date/title',
	title     => 'title',
);

# Pure: validate query parameters. Returns ( \%params ) or ( undef, \%errors ).
sub parse_params
{
	my( $q ) = @_;
	my( %p, %err );

	my $text = defined $q->{q} ? $q->{q} : '';
	$text =~ s/[\x00-\x1f\x7f]+/ /g;
	$text =~ s/\A\s+|\s+\z//g;
	if( length( $text ) > MAX_Q ) { $err{q} = 'Kata kunci paling banyak ' . MAX_Q . ' karakter.' }
	$p{q} = $text;

	if( defined $q->{type} && length $q->{type} )
	{
		if( $q->{type} =~ /\A[A-Za-z0-9_-]{1,64}\z/ ) { $p{type} = $q->{type} }
		else { $err{type} = 'Jenis karya tidak valid.' }
	}
	if( defined $q->{division} && length $q->{division} )
	{
		if( $q->{division} =~ /\A[A-Za-z0-9_.:-]{1,64}\z/ ) { $p{division} = $q->{division} }
		else { $err{division} = 'Program studi tidak valid.' }
	}
	if( defined $q->{subject} && length $q->{subject} )
	{
		if( $q->{subject} =~ /\A[A-Za-z0-9_.:-]{1,64}\z/ ) { $p{subject} = $q->{subject} }
		else { $err{subject} = 'Subjek tidak valid.' }
	}
	foreach my $k ( qw( year_from year_to ) )
	{
		next if !defined $q->{$k} || !length $q->{$k};
		if( $q->{$k} =~ /\A[12][0-9]{3}\z/ ) { $p{$k} = $q->{$k} + 0 }
		else { $err{$k} = 'Tahun tidak valid.' }
	}
	if( $p{year_from} && $p{year_to} && $p{year_from} > $p{year_to} )
	{
		$err{year_to} = 'Tahun akhir harus sama atau setelah tahun awal.';
	}
	foreach my $k ( qw( has_files open_only ) )
	{
		$p{$k} = defined $q->{$k} && $q->{$k} =~ /\A(?:1|true)\z/ ? 1 : 0;
	}

	my $sort = defined $q->{sort} && length $q->{sort} ? $q->{sort} : ( length $p{q} ? 'relevance' : 'latest' );
	if( exists $SORTS{$sort} ) { $p{sort} = $sort }
	else { $err{sort} = 'Urutan tidak dikenal.' }

	my $limit = defined $q->{limit} && length $q->{limit} ? $q->{limit} : DEF_LIMIT;
	if( $limit =~ /\A[0-9]{1,3}\z/ && $limit >= 1 ) { $p{limit} = $limit > MAX_LIMIT ? MAX_LIMIT : $limit + 0 }
	else { $err{limit} = 'Batas hasil tidak valid.' }

	my $cursor = defined $q->{cursor} && length $q->{cursor} ? $q->{cursor} : 0;
	if( $cursor =~ /\A[0-9]{1,5}\z/ && $cursor <= MAX_OFFSET ) { $p{offset} = $cursor + 0 }
	else { $err{cursor} = 'Halaman tidak valid.' }

	return ( undef, \%err ) if %err;
	return ( \%p );
}

# Returns { eprints => [ ... ], total => n, next_cursor => n|undef, engine => 'xapian'|'internal' }.
sub run
{
	my( $repo, $p ) = @_;

	my $ds = EPrints::KlarasConnect::Compat::dataset( $repo, 'archive' )
		or die "klaras_connect: no archive dataset\n";

	my $result;
	if( length $p->{q} && !$p->{year_from} && !$p->{year_to} && EPrints::KlarasConnect::Compat::has_xapian( $repo ) )
	{
		$result = eval { _xapian( $repo, $ds, $p ) };
		$repo->log( "klaras_connect: xapian search failed, using internal: $@" ) if !$result && $@;
	}
	$result ||= _internal( $repo, $ds, $p );

	my $next = $p->{offset} + $p->{limit};
	$result->{next_cursor} = ( $next < $result->{total} && $next <= MAX_OFFSET ) ? $next : undef;
	return $result;
}

sub _filter_fields
{
	my( $ds, $p ) = @_;
	my @f;
	push @f, [ 'type', $p->{type} ] if defined $p->{type} && EPrints::KlarasConnect::Compat::has_field( $ds, 'type' );
	push @f, [ 'divisions', $p->{division} ] if defined $p->{division} && EPrints::KlarasConnect::Compat::has_field( $ds, 'divisions' );
	push @f, [ 'subjects', $p->{subject} ] if defined $p->{subject} && EPrints::KlarasConnect::Compat::has_field( $ds, 'subjects' );
	if( EPrints::KlarasConnect::Compat::has_field( $ds, 'full_text_status' ) )
	{
		if( $p->{open_only} ) { push @f, [ 'full_text_status', 'public' ] }
		elsif( $p->{has_files} ) { push @f, [ 'full_text_status', 'public restricted', 'ANY' ] }
	}
	return @f;
}

sub _internal
{
	my( $repo, $ds, $p ) = @_;

	my $order = $SORTS{ $p->{sort} };
	$order = '-date/title' if !defined $order;    # internal search has no relevance score

	my $search = $ds->prepare_search(
		satisfy_all  => 1,
		custom_order => $order,
		limit        => $p->{offset} + $p->{limit},
	);

	if( length $p->{q} )
	{
		my $conf = $repo->config( 'search', 'simple' );
		my $fields = ref $conf eq 'HASH' && ref $conf->{search_fields} eq 'ARRAY'
			? $conf->{search_fields}->[0]->{meta_fields}
			: undef;
		$fields = [qw( title abstract creators_name keywords )] if ref $fields ne 'ARRAY';
		my @f = grep { defined } map { my $n = $_; $n =~ s/[^a-z0-9_.]//g; eval { $ds->field( $n ) } } @$fields;
		die "klaras_connect: no searchable fields\n" if !@f;
		$search->add_field( fields => \@f, value => $p->{q}, match => 'IN', merge => 'ALL' );
	}

	foreach my $f ( _filter_fields( $ds, $p ) )
	{
		my( $name, $value, $merge ) = @$f;
		$search->add_field( fields => [ $ds->field( $name ) ], value => $value, match => 'EQ', merge => ( $merge || 'ALL' ) );
	}

	if( ( $p->{year_from} || $p->{year_to} ) && EPrints::KlarasConnect::Compat::has_field( $ds, 'date' ) )
	{
		my $range = ( $p->{year_from} || '' ) . '-' . ( $p->{year_to} || '' );
		$search->add_field( fields => [ $ds->field( 'date' ) ], value => $range, match => 'EQ' );
	}

	my $list = $search->perform_search;
	my $total = $list->count;
	my @eprints = $list->slice( $p->{offset}, $p->{limit} );
	$list->dispose if $list->can( 'dispose' );

	return { eprints => \@eprints, total => $total + 0, engine => 'internal' };
}

sub _xapian
{
	my( $repo, $ds, $p ) = @_;

	my $plugin = $repo->plugin( 'Search::Xapian', session => $repo, dataset => $ds )
		or die "no xapian plugin\n";
	require Search::Xapian;

	my $path = $repo->config( 'variables_path' ) . '/xapian';
	my $xapian = Search::Xapian::Database->new( $path );

	my $qp = Search::Xapian::QueryParser->new( $xapian );
	$qp->set_stemmer( $plugin->stemmer );
	$qp->set_stopper( $plugin->stopper );
	$qp->set_stemming_strategy( Search::Xapian::STEM_SOME() );
	$qp->set_default_op( Search::Xapian::OP_AND() );

	my $query = Search::Xapian::Query->new( '_dataset:' . $ds->base_id );
	foreach my $f ( @{ $ds->{filters} || [] } )
	{
		$query = Search::Xapian::Query->new( Search::Xapian::OP_AND(), $query,
			Search::Xapian::Query->new( $f->{meta_fields}->[0] . ':' . $f->{value} ) );
	}
	foreach my $f ( _filter_fields( $ds, $p ) )
	{
		my( $name, $value ) = @$f;
		my @terms = map { Search::Xapian::Query->new( "$name:$_" ) } split / /, $value;
		my $term = @terms == 1 ? $terms[0] : Search::Xapian::Query->new( Search::Xapian::OP_OR(), @terms );
		$query = Search::Xapian::Query->new( Search::Xapian::OP_AND(), $query, $term );
	}

	# Plain words only: boolean/wildcard flags off, so a member's input can
	# never become an expensive wildcard expansion.
	$query = Search::Xapian::Query->new( Search::Xapian::OP_AND(), $query,
		$qp->parse_query( $p->{q}, Search::Xapian::FLAG_PHRASE() ) );

	my $enq = $xapian->enquire( $query );
	my $order = $SORTS{ $p->{sort} };
	if( defined $order )
	{
		my $sorter = Search::Xapian::MultiValueSorter->new;
		my $added = 0;
		foreach my $part ( split /\//, $order )
		{
			my $reverse = $part =~ s/^-// ? 1 : 0;
			my $key = join '.', $ds->base_id, $part, $repo->get_langid;
			my $idx = $xapian->get_metadata( $key );
			next if !length $idx;
			$sorter->add( $idx, $reverse );
			$added++;
		}
		$enq->set_sort_by_key_then_relevance( $sorter ) if $added;
	}

	my $mset = $enq->get_mset( $p->{offset}, $p->{limit}, COUNT_EXACT );
	my @ids = grep { /\A[0-9]+\z/ } map { $_->get_document->get_data } $mset->items;
	my @eprints = grep { defined } map { eval { $ds->dataobj( $_ ) } } @ids;

	return { eprints => \@eprints, total => $mset->get_matches_estimated + 0, engine => 'xapian' };
}

1;
