from meteor_reasoner.utils.loader import load_dataset, load_program
from meteor_reasoner.materialization.materialize import coalescing_d, naive_immediate_consequence_operator
from meteor_reasoner.materialization.materialize import build_index
from meteor_reasoner.utils import parser as parser
from meteor_reasoner.materialization.naive_join import *

def entail(dataset, fact):
    predicate, entity, interval = parser.parse_str_fact(fact)

    if predicate in dataset:
       if entity in dataset[predicate]:
           for intv in dataset[predicate][entity]:
                if interval.left_value >= intv.left_value and interval.right_value <= intv.right_value:
                    return True
    return False


# data = ["A(a)@1", "B(a)@[1,2]", "C@(1,2]"]
# program = ["A(X):-Diamondminus[1,2]A(X)", "D(X):- Boxminus[1,2]A(X), B(X)Since[1,2]C"]

# data = ["A@[1,2]", "C@[4,6]"]
# program = ["B:- Diamondminus[1,1]A, Diamondplus[1,2]C"]
# data = ["A@[1,1]"]
# program = ["A:- Diamondminus[1,1]A"]
program = ["A:- Diamondplus[6,10]B"]
data=["B@[3, 10]"]
dataset = load_dataset(data)
program = load_program(program)

d_index = build_index(dataset)

delta_new = defaultdict(lambda: defaultdict(list))
naive_join(program[0], dataset, delta_new, d_index)


print("derived facts:")
print_dataset(delta_new)
print("dataset:")
for predicate in delta_new:
  if predicate not in dataset:
      dataset[predicate] = delta_new[predicate]
  else:
      for entity in delta_new[predicate]:
          dataset[predicate][entity] = dataset[predicate][entity] + delta_new[predicate][entity]
  coalescing_d(dataset)

print_dataset(dataset)
# print(entail(dataset, "B@[1.5,5]"))