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};
  my @deps = $state->action_dependencies(map $_->id, @vars);
  my $action = $self->builder->(map $state->resolve_value($_), @vars)
                    ->but(dependencies => \@deps);
  my ($fact_type, $value) = $action->expected_effect;
  my $id = $vars[0]->id;
  my $var = $state->by_id->{$id}->with_action($action);
  my $fact_set = $state->facts->{$fact_type}->with_value($value);
  $state->but(
            by_id => { %{$state->by_id}, $id => $var },
            facts => { %{$state->facts}, $fact_type => $fact_set },
          )
        ->then($self->next);
}

1;
