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., "(robot-at robot1 tile_0_1)".
    - `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 FloortileHeuristic(Heuristic):
    """
    A domain-dependent heuristic for the Floortile domain.

    # Summary
    This heuristic estimates the number of actions required to paint all tiles according to the goal conditions.
    It considers the following factors:
    - The number of tiles that still need to be painted.
    - The distance between the robot's current position and the tiles that need to be painted.
    - The number of color changes required for the robot to paint the tiles with the correct colors.

    # Assumptions
    - The robot can only paint adjacent tiles (up, down, left, right).
    - The robot must change its color if it needs to paint a tile with a different color than the one it currently holds.
    - The robot can move freely between tiles as long as they are clear.

    # Heuristic Initialization
    - Extract the goal conditions for each tile (i.e., the required color for each tile).
    - Extract the static facts (e.g., adjacency relationships between tiles) to compute distances.
    - Initialize data structures to store the goal colors and adjacency relationships.

    # Step-By-Step Thinking for Computing Heuristic
    1. Identify the tiles that still need to be painted by comparing the current state with the goal conditions.
    2. For each unpainted tile, compute the Manhattan distance between the robot's current position and the tile.
    3. If the robot does not have the correct color for a tile, add a cost for changing the color.
    4. Sum the distances and color change costs to estimate the total number of actions required.
    """

    def __init__(self, task):
        """
        Initialize the heuristic by extracting:
        - Goal conditions for each tile.
        - Static facts (adjacency relationships between tiles).
        """
        self.goals = task.goals  # Goal conditions.
        static_facts = task.static  # Facts that are not affected by actions.

        # Map each tile to its required color in the goal state.
        self.goal_colors = {}
        for goal in self.goals:
            predicate, *args = get_parts(goal)
            if predicate == "painted":
                tile, color = args
                self.goal_colors[tile] = color

        # Store adjacency relationships between tiles.
        self.adjacent = {}
        for fact in static_facts:
            predicate, *args = get_parts(fact)
            if predicate in ["up", "down", "left", "right"]:
                tile1, tile2 = args
                if tile1 not in self.adjacent:
                    self.adjacent[tile1] = set()
                self.adjacent[tile1].add(tile2)

    def __call__(self, node):
        """Compute an estimate of the minimal number of required actions."""
        state = node.state  # Current world state.

        # Identify the robot's current position and color.
        robot_position = None
        robot_color = None
        for fact in state:
            predicate, *args = get_parts(fact)
            if predicate == "robot-at":
                robot, position = args
                robot_position = position
            elif predicate == "robot-has":
                robot, color = args
                robot_color = color

        total_cost = 0  # Initialize action cost counter.

        # Iterate over all tiles that need to be painted.
        for tile, goal_color in self.goal_colors.items():
            # Check if the tile is already painted with the correct color.
            if f"(painted {tile} {goal_color})" in state:
                continue

            # Compute the Manhattan distance between the robot and the tile.
            # For simplicity, assume tiles are arranged in a grid and named accordingly.
            # Extract coordinates from tile names (e.g., "tile_1_2" -> (1, 2)).
            x1, y1 = map(int, robot_position.split("_")[1:])
            x2, y2 = map(int, tile.split("_")[1:])
            distance = abs(x1 - x2) + abs(y1 - y2)

            # Add the distance to the total cost.
            total_cost += distance

            # If the robot does not have the correct color, add a cost for changing the color.
            if robot_color != goal_color:
                total_cost += 1  # Cost for changing color.

        # Return the estimated cost to goal state.
        return total_cost
