from fnmatch import fnmatch
from heuristics.heuristic_base import Heuristic


def get_parts(fact):
    """Extract the components of a PDDL fact by removing parentheses and splitting the string."""
    return fact[1:-1].split()


def match(fact, *args):
    """
    Check if a PDDL fact matches a given pattern.

    - `fact`: The complete fact as a string, e.g., "(at package1 location1)".
    - `args`: The expected pattern (wildcards `*` allowed).
    - Returns `True` if the fact matches the pattern, else `False`.
    """
    parts = get_parts(fact)
    return all(fnmatch(part, arg) for part, arg in zip(parts, args))


class transport16Heuristic(Heuristic):
    """
    A domain-dependent heuristic for the transport domain.

    # Summary
    This heuristic estimates the number of actions required to move all packages to their goal locations.
    It considers the number of packages at the wrong locations and estimates the number of pick-up, drop, and drive actions needed.

    # Assumptions
    - Each package needs to be picked up, transported, and dropped at its destination.
    - The heuristic does not consider vehicle capacity or size constraints.
    - It assumes that there are enough vehicles to transport all packages.
    - It assumes that the road network is fully connected.

    # Heuristic Initialization
    - Extract the goal locations for each package from the task goals.
    - Store the road network information from the static facts.

    # Step-By-Step Thinking for Computing Heuristic
    1. Extract the current locations of all packages from the state.
    2. For each package, check if it is at its goal location.
    3. If a package is not at its goal location, estimate the number of actions required to move it to the goal:
       - One pick-up action.
       - One drive action (to the goal location).
       - One drop action.
    4. Sum the estimated number of actions for all packages not at their goal locations.
    """

    def __init__(self, task):
        """
        Initialize the heuristic by extracting goal locations and road network information.
        """
        self.goals = task.goals
        static_facts = task.static

        # Extract goal locations for each package.
        self.goal_locations = {}
        for goal in self.goals:
            if match(goal, "at", "*", "*"):
                package = get_parts(goal)[1]
                location = get_parts(goal)[2]
                self.goal_locations[package] = location

        # Extract road network information.
        self.roads = set()
        for fact in static_facts:
            if match(fact, "road", "*", "*"):
                location1 = get_parts(fact)[1]
                location2 = get_parts(fact)[2]
                self.roads.add((location1, location2))

    def __call__(self, node):
        """
        Compute an estimate of the number of actions required to reach the goal state.
        """
        state = node.state
        incorrect_packages = 0

        # Extract current locations of packages.
        current_locations = {}
        for fact in state:
            if match(fact, "at", "*", "*"):
                package = get_parts(fact)[1]
                location = get_parts(fact)[2]
                current_locations[package] = location

        # Count packages not at their goal locations.
        for package, goal_location in self.goal_locations.items():
            if package not in current_locations or current_locations[package] != goal_location:
                incorrect_packages += 1

        # Estimate the number of actions required for each incorrect package (pick-up, drive, drop).
        heuristic_value = incorrect_packages * 3

        # If the goal is already reached, return 0.
        if node.state >= self.goals:
            return 0

        return heuristic_value
