package DX::RuleSet;

use Moo;
use DX::Op::SetupScope;
use DX::Op::CallRule;
use DX::Op::MemberOf;
use DX::Op::ApplyConstraint;
use DX::Op::Return;
use DX::Op::Cut;
use DX::Op::Backtrack;
use DX::Op::Observe;
use DX::Op::Not;
use DX::Op::ProposeAction;
use DX::Op::Materialize;
use DX::Op::Prop;
use DX::Op::Exists;
use List::Util qw(reduce);

has rules => (is => 'ro', default => sub { {} });

sub add_rule {
  my ($self, $name, $vars, @body) = @_;
  my $full_name = join('/', $name, scalar @$vars);
  push @{$self->rules->{$full_name}}, $self->_make_rule($vars, @body);
  return $self;
}

sub _make_rule {
  my ($self, $vars, @body) = @_;
  my $head = $self->expand_and_link(DX::Op::Return->new, @body);
  DX::Op::SetupScope->new(arg_names => $vars, next => $head);
}

sub expand_and_link {
  my ($self, $last, @body) = @_;
  return reduce { $b->but(next => $a) }
           $last,
           reverse map $self->expand($_), @body;
}

sub expand {
  my ($self, $thing) = @_;
  if (ref($thing) eq 'ARRAY') {
    my ($type, @rest) = @$thing;
    if ($self->can(my $expand_meth = "_expand_op_${type}")) {
      return $self->$expand_meth(@rest);
    }
    return $self->_expand_call(@$thing);
  }
  return $thing;
}

sub _expand_call {
  my ($self, $name, @args) = @_;
  DX::Op::CallRule->new(rule_name => $name, rule_args => \@args);
}

sub _expand_op_cut { return DX::Op::Cut->new }

sub _expand_op_fail { return DX::Op::Backtrack->new }

sub _expand_op_not {
  my ($self, @contents) = @_;
  my $cut = DX::Op::Cut->new(next => DX::Op::Backtrack->new);
  DX::Op::Not->new(
    body => $self->expand_and_link($cut, @contents)
  );
}

sub _expand_op_member_of {
  my ($self, $member_var, $coll_var) = @_;
  DX::Op::MemberOf->new(
    member_var => $member_var,
    coll_var => $coll_var,
  );
}

sub _expand_op_constrain {
  my ($self, $vars, $constraint) = @_;
  DX::Op::ApplyConstraint->new(
    vars => $vars,
    constraint => $constraint
  );
}

sub _expand_op_observe {
  my ($self, $vars, $builder) = @_;
  DX::Op::Observe->new(
    vars => $vars,
    builder => $builder,
  );
}

sub _expand_op_act {
  my ($self, $vars, $builder) = @_;
  DX::Op::ProposeAction->new(
    vars => $vars,
    builder => $builder,
  );
}

sub _expand_op_materialize {
  my ($self, $var_name) = @_;
  DX::Op::Materialize->new(var_name => $var_name);
}

sub _expand_op_prop {
  my ($self, @args) = @_;
  my %new; @new{qw(of name value)} = @args;
  DX::Op::Prop->new(%new);
}

sub _expand_op_exists {
  my ($self, $vars, @body) = @_;
  DX::Op::Exists->new(
    vars => $vars,
    body => $self->expand_and_link(DX::Op::Return->new, @body)
  );
}

1;
