"""Elevator system: a controller assigns hall calls to cars; each car runs the SCAN (elevator) algorithm."""
from __future__ import annotations

from enum import Enum
from typing import List, Set


class Direction(Enum):
    UP = 1
    DOWN = -1
    IDLE = 0


class Car:
    def __init__(self, car_id: int, floor: int = 0):
        self.car_id, self.floor = car_id, floor
        self.direction = Direction.IDLE
        self.stops: Set[int] = set()

    def add_stop(self, floor: int) -> None:
        if floor != self.floor:
            self.stops.add(floor)
        if self.direction is Direction.IDLE and self.stops:
            self.direction = Direction.UP if floor > self.floor else Direction.DOWN

    def cost(self, floor: int, direction: Direction) -> int:
        """Rough distance cost: cheap if idle or already heading toward the floor in the same direction."""
        distance = abs(self.floor - floor)
        if self.direction is Direction.IDLE:
            return distance
        heading_toward = (floor - self.floor) * self.direction.value >= 0
        if heading_toward and direction is self.direction:
            return distance
        return distance + 2 * len(self.stops) + 10  # must finish current sweep first

    def step(self) -> List[int]:
        """Move one floor; return floors where doors opened during this step."""
        if not self.stops:
            self.direction = Direction.IDLE
            return []
        ahead = [s for s in self.stops if (s - self.floor) * self.direction.value > 0]
        if not ahead:  # nothing left in this direction: reverse (SCAN)
            self.direction = Direction.DOWN if self.direction is Direction.UP else Direction.UP
        self.floor += self.direction.value
        opened = []
        if self.floor in self.stops:
            self.stops.remove(self.floor)
            opened.append(self.floor)
        if not self.stops:
            self.direction = Direction.IDLE
        return opened


class ElevatorController:
    def __init__(self, cars: int, floors: int):
        self.floors = floors
        self.cars = [Car(i) for i in range(cars)]

    def hall_call(self, floor: int, direction: Direction) -> int:
        if not 0 <= floor < self.floors:
            raise ValueError("no such floor")
        car = min(self.cars, key=lambda c: (c.cost(floor, direction), c.car_id))
        car.add_stop(floor)
        return car.car_id

    def car_call(self, car_id: int, floor: int) -> None:
        self.cars[car_id].add_stop(floor)

    def step(self) -> dict:
        return {car.car_id: car.step() for car in self.cars}
