package prolog.builtins

import interpreter.FileLoader
import prolog.Answers
import prolog.Substitutions
import prolog.ast.logic.LogicOperand
import prolog.ast.logic.LogicOperator
import prolog.ast.terms.Atom
import prolog.ast.terms.Operator
import prolog.ast.terms.Term
import prolog.logic.applySubstitution

class Consult(val file: Term) : Operator("consult", rightOperand = file) {
    private val fileLoader = FileLoader()

    override fun satisfy(subs: Substitutions): Answers {
        val fileAtom = applySubstitution(file, subs)
        require(fileAtom is Atom) { "File name must be an atom" }

        var filePath = fileAtom.name
        if (!filePath.endsWith(".pl")) {
            filePath += ".pl"
        }

        try {
            fileLoader.load(filePath)
            return sequenceOf(Result.success(emptyMap()))
        } catch (e: Exception) {
            return sequenceOf(Result.failure(e))
        }
    }

    override fun toString(): String = "consult($file)"
}

class Initialization(val goal: LogicOperand) : LogicOperator(":-", rightOperand = goal) {
    override fun satisfy(subs: Substitutions): Answers = goal.satisfy(subs).take(1)
    override fun toString(): String = goal.toString()
}
