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 assumes that the lift can serve passengers in an optimal order.

    # 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 at their destination).
        - Check which passengers are still at their origin (they need to be boarded and served).
    2. Compute the cost of serving each passenger:
        - For passengers not yet boarded:
            - Move the lift to their origin floor (if not already there).
            - Board the passenger.
            - Move the lift to their destination floor.
            - Serve the passenger.
        - For passengers already boarded:
            - Move the lift to their destination floor (if not already there).
            - Serve the passenger.
    3. Sum the total cost of actions required to serve all 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 the 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 the `above` relationships between floors.
        self.above_relations = {
            (get_parts(fact)[1], get_parts(fact)[2])
            for fact in static_facts
            if match(fact, "above", "*", "*")
        }

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

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

        # 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 not yet boarded.
        unboarded_passengers = {
            get_parts(fact)[1]
            for fact in state
            if match(fact, "origin", "*", "*")
        } - served_passengers - boarded_passengers

        total_cost = 0  # Initialize action cost counter.

        # Handle unboarded passengers.
        for passenger in unboarded_passengers:
            # Move the lift to the passenger's origin floor.
            origin_floor = get_parts(
                next(fact for fact in state if match(fact, "origin", passenger, "*"))
            )[2]
            if lift_at != origin_floor:
                total_cost += 1  # Move the lift.
                lift_at = origin_floor

            # Board the passenger.
            total_cost += 1

            # Move the lift to the passenger's destination floor.
            destin_floor = self.destin_floors[passenger]
            if lift_at != destin_floor:
                total_cost += 1  # Move the lift.
                lift_at = destin_floor

            # Serve the passenger.
            total_cost += 1

        # Handle boarded passengers.
        for passenger in boarded_passengers:
            # Move the lift to the passenger's destination floor.
            destin_floor = self.destin_floors[passenger]
            if lift_at != destin_floor:
                total_cost += 1  # Move the lift.
                lift_at = destin_floor

            # Serve the passenger.
            total_cost += 1

        return total_cost
