package DX::SearchState;

use Types::Standard qw(Maybe);
use DX::Step::InvokeNextPredicate;
use DX::Class;

has current_hypothesis => (is => 'ro', isa => Hypothesis, required => 1);

has next_step => (is => 'ro', isa => Maybe[Step]);

has propositions => (is => 'ro', isa => PropositionSequence, required => 1);

has alternatives => (is => 'ro', isa => AlternativeList, required => 1);

sub next_proposition {
  my ($self, $hyp) = @_;
  $hyp ||= $self->current_hypothesis;
  $self->propositions->members->[
    $hyp->resolved_propositions->resolved_count
  ];
}

sub new_for {
  my ($class, $hyp, $props) = @_;
  $class->new(
    current_hypothesis => $hyp,
    alternatives => [],
    next_step => DX::Step::InvokeNextPredicate->new(
      proposition => $props->members->[0],
    ),
    propositions => $props,
  );
}

sub with_one_step {
  my ($self) = @_;
  my $hyp = $self->current_hypothesis;
  return undef unless my $step = $self->next_step;
  my ($first_alt, @rest_alt) = my @alt = @{$self->alternatives};
  my ($new_hyp, $alt_step) = $step->apply_to($hyp);
  if ($new_hyp) {
    return $self->but(
      current_hypothesis => $new_hyp,
      alternatives => [
        ($alt_step
          ? [ $hyp, $alt_step ]
          : ()),
        @alt
      ],
      next_step => DX::Step::InvokeNextPredicate->new(
        proposition => $self->next_proposition($new_hyp),
      ),
    );
  }
  if ($alt_step) {
    return $self->but(next_step => $alt_step);
  }
  return undef unless $first_alt;
  trace 'search.backtrack.rewind_to' => $first_alt->[1];
  return $self->but(
    current_hypothesis => $first_alt->[0],
    alternatives => \@rest_alt,
    next_step => $first_alt->[1],
  );
}

sub find_solution {
  my $state = $_[0];
  while ($state and $state->next_proposition) {
    $state = $state->with_one_step;
  }
  trace 'search.solution.hyp' => $state->current_hypothesis if $state;
  return $state;
}

sub force_backtrack {
  my ($self) = @_;
  my ($first_alt, @rest_alt) = @{$self->alternatives};
  return undef unless $first_alt;
  trace 'search.backtrack.forced' => $first_alt->[0];
  return ref($self)->new(
    current_hypothesis => $first_alt->[0],
    next_step => $first_alt->[1],
    alternatives => \@rest_alt,
    propositions => $self->propositions,
  );
}

sub find_next_solution {
  my ($self) = @_;
  return undef unless my $bt = $self->force_backtrack;
  return $bt->find_solution;
}

1;
