package DX::Op::ProposeAction;

use DX::ObservationRequired;
use Moo;

with 'DX::Role::Op';

has vars => (is => 'ro', required => 1);
has builder => (is => 'ro', required => 1);

has _arg_map => (is => 'lazy', builder => sub {
  my ($self) = @_;
  my $name = 'arg0';
  +{ map +($name++, $_), @{$self->vars} };
});

sub run {
  my ($self, $state) = @_;
  ($state, my %args) = $self->_expand_args($state, %{$self->_arg_map});
  my @vars = @args{sort keys %args};
  return $state->backtrack unless @vars == grep $_->is_bound, @vars;
  return $state->backtrack unless $state->allow_actions;
  my @deps = $state->action_dependencies(map $_->id, @vars);
  my $action = $self->builder->(map $state->resolve_value($_), @vars)
                    ->but(dependencies => \@deps);
  my ($rec_state, $action_id) = $state->record_action($action);
  my @effect = $action->expected_effect;
  my %facts = %{$state->facts};
  while (my ($fact_type, $value) = splice(@effect, 0, 2)) {
    my $final_value = $value->but(required_action => $action_id);
    $facts{$fact_type} = $facts{$fact_type}->with_value($final_value);
  }
  $rec_state->but(facts => \%facts)
            ->then($self->next);
}

1;
