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., "(origin p1 f1)".
    - `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 MiconicHeuristic(Heuristic):
    """
    A domain-dependent heuristic for the Miconic domain.

    # Summary
    This heuristic estimates the number of actions required to serve all passengers by considering:
    - The number of passengers still to be served.
    - The current position of the lift.
    - The origin and destination floors of each passenger.

    # Assumptions:
    - The lift can move between floors using the `up` and `down` actions.
    - Passengers must be boarded from their origin floor and served at their destination floor.
    - The heuristic does not need to be admissible, so it can overestimate the number of actions.

    # Heuristic Initialization
    - Extract the goal conditions (all passengers must be served).
    - Extract static facts, such as the `above` relationships between floors and the `destin` of each passenger.

    # Step-By-Step Thinking for Computing Heuristic
    1. Identify the current state of the lift and the passengers:
       - Check which passengers are already served.
       - Check which passengers are boarded.
       - Check the current floor of the lift.
    2. For each unserved passenger:
       - If the passenger is not boarded, estimate the cost to board them:
         - Move the lift to their origin floor.
         - Perform the `board` action.
       - If the passenger is boarded, estimate the cost to serve them:
         - Move the lift to their destination floor.
         - Perform the `depart` action.
    3. Sum the estimated costs for all unserved passengers.
    """

    def __init__(self, task):
        """Initialize the heuristic by extracting goal conditions and static facts."""
        self.goals = task.goals  # Goal conditions.
        static_facts = task.static  # Facts that are not affected by actions.

        # Extract destination floors for each passenger.
        self.destin_floors = {
            get_parts(fact)[1]: get_parts(fact)[2]
            for fact in static_facts
            if match(fact, "destin", "*", "*")
        }

        # Extract origin floors for each passenger.
        self.origin_floors = {
            get_parts(fact)[1]: get_parts(fact)[2]
            for fact in static_facts
            if match(fact, "origin", "*", "*")
        }

        # Extract the `above` relationships between floors.
        self.above_relationships = {
            (get_parts(fact)[1], get_parts(fact)[2])
            for fact in static_facts
            if match(fact, "above", "*", "*")
        }

    def __call__(self, node):
        """Estimate the number of actions required to serve all passengers."""
        state = node.state  # Current world state.

        # Identify which passengers are already served.
        served_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "served", "*")
        }

        # Identify which passengers are boarded.
        boarded_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "boarded", "*")
        }

        # Identify the current floor of the lift.
        lift_at = None
        for fact in state:
            if match(fact, "lift-at", "*"):
                lift_at = get_parts(fact)[1]
                break

        total_cost = 0  # Initialize the heuristic cost.

        for passenger in self.destin_floors:
            if passenger in served_passengers:
                continue  # Passenger is already served.

            if passenger in boarded_passengers:
                # Passenger is boarded but not served.
                # Estimate the cost to move the lift to the destination floor and perform the `depart` action.
                destin_floor = self.destin_floors[passenger]
                if lift_at != destin_floor:
                    # Estimate the number of floors to move.
                    total_cost += self._estimate_floors_to_move(lift_at, destin_floor)
                total_cost += 1  # Perform the `depart` action.
            else:
                # Passenger is not boarded.
                # Estimate the cost to move the lift to the origin floor, perform the `board` action,
                # then move to the destination floor and perform the `depart` action.
                origin_floor = self.origin_floors[passenger]
                destin_floor = self.destin_floors[passenger]

                if lift_at != origin_floor:
                    # Estimate the number of floors to move to the origin floor.
                    total_cost += self._estimate_floors_to_move(lift_at, origin_floor)
                total_cost += 1  # Perform the `board` action.

                if origin_floor != destin_floor:
                    # Estimate the number of floors to move to the destination floor.
                    total_cost += self._estimate_floors_to_move(origin_floor, destin_floor)
                total_cost += 1  # Perform the `depart` action.

        return total_cost

    def _estimate_floors_to_move(self, from_floor, to_floor):
        """
        Estimate the number of floors the lift needs to move between `from_floor` and `to_floor`.
        """
        if from_floor == to_floor:
            return 0

        # Count the number of floors between `from_floor` and `to_floor` using the `above` relationships.
        count = 0
        current_floor = from_floor
        while current_floor != to_floor:
            # Find the next floor in the direction of `to_floor`.
            if (current_floor, to_floor) in self.above_relationships:
                count += 1
                current_floor = to_floor
            else:
                # Move one floor at a time.
                for floor1, floor2 in self.above_relationships:
                    if floor1 == current_floor:
                        count += 1
                        current_floor = floor2
                        break
                else:
                    # No path found (should not happen in valid states).
                    return float('inf')

        return count
