"""Logic verification core — truth tables, validity checking, classification."""

import itertools
from sympy import Symbol
from sympy.logic.boolalg import Implies, And, Or, Not


class LogicCore:
    def __init__(self):
        self.variables = set()

    def generate_truth_table(self, expr, variables):
        """Generates a full truth table.

        expr: SymPy expression object
        variables: list of SymPy Symbols
        """
        table = []
        for values in itertools.product([False, True], repeat=len(variables)):
            interp = dict(zip(variables, values))
            result = expr.subs(interp)
            table.append((interp, bool(result)))
        return table

    def check_validity(self, premises: list, conclusion):
        """Checks if Premises -> Conclusion is a Tautology.

        Returns (is_valid, counterexample)
        """
        import sympy

        if not premises:
            combined_premises = sympy.true
        else:
            combined_premises = premises[0]
            for p in premises[1:]:
                combined_premises = And(combined_premises, p)

        argument = Implies(combined_premises, conclusion)
        atoms = argument.atoms(Symbol)
        variables = list(atoms)

        for values in itertools.product([False, True], repeat=len(variables)):
            interp = dict(zip(variables, values))
            if not argument.subs(interp):
                return False, interp

        return True, None

    def classify(self, expr):
        """Returns TAUTOLOGY, CONTRADICTION, or CONTINGENT."""
        atoms = list(expr.atoms(Symbol))
        table = self.generate_truth_table(expr, atoms)
        results = [res for _, res in table]

        if all(results):
            return "TAUTOLOGY"
        if not any(results):
            return "CONTRADICTION"
        return "CONTINGENT"
