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 current position of the lift.
    - The origin and destination floors of each passenger.
    - Whether passengers are already boarded or served.

    # Assumptions:
    - The lift can move between floors using the `up` and `down` actions.
    - Passengers must be boarded before they can be served.
    - 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 (no further actions needed).
       - Check which passengers are boarded (they need to be served).
       - Check which passengers are still at their origin floors (they need to be boarded and served).
    2. For each passenger not yet served:
       - If the passenger is not boarded, estimate the number of actions to board them:
         - Move the lift to their origin floor.
         - Perform the `board` action.
       - If the passenger is boarded, estimate the number of actions to serve them:
         - Move the lift to their destination floor.
         - Perform the `depart` action.
    3. Sum the estimated actions for all passengers to get the total heuristic value.
    """

    def __init__(self, task):
        """Initialize the heuristic by extracting goal conditions and static facts."""
        self.goals = task.goals  # Goal conditions (all passengers must be served).
        static_facts = task.static  # Static facts (e.g., `above` relationships).

        # 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 `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 passengers who are already served.
        served_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "served", "*")
        }

        # Identify passengers who are boarded but not yet served.
        boarded_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "boarded", "*")
        } - served_passengers

        # Identify passengers who are still at their origin floors.
        origin_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "origin", "*", "*")
        } - served_passengers - boarded_passengers

        # Get the current floor of the lift.
        lift_floor = next(
            get_parts(fact)[1]
            for fact in state
            if match(fact, "lift-at", "*")
        )

        total_cost = 0  # Initialize the heuristic cost.

        # Estimate actions for passengers still at their origin floors.
        for passenger in origin_passengers:
            origin_floor = next(
                get_parts(fact)[2]
                for fact in state
                if match(fact, "origin", passenger, "*")
            )
            # Move the lift to the origin floor.
            total_cost += self._estimate_move_cost(lift_floor, origin_floor)
            # Board the passenger.
            total_cost += 1
            # Update the lift's current floor.
            lift_floor = origin_floor

        # Estimate actions for boarded passengers.
        for passenger in boarded_passengers:
            destin_floor = self.destin_floors[passenger]
            # Move the lift to the destination floor.
            total_cost += self._estimate_move_cost(lift_floor, destin_floor)
            # Depart the passenger.
            total_cost += 1
            # Update the lift's current floor.
            lift_floor = destin_floor

        return total_cost

    def _estimate_move_cost(self, current_floor, target_floor):
        """
        Estimate the number of actions required to move the lift from `current_floor` to `target_floor`.
        """
        if current_floor == target_floor:
            return 0
        # Count the number of floors between current and target.
        # Since the `above` relationships are transitive, we can assume a direct path.
        return abs(int(current_floor[1:]) - int(target_floor[1:]))
