import csv
import io
import textwrap

from app.utils.constants import GENERAL_ROOM_DETAILS


def _load_rooms() -> list[dict]:
    reader = csv.DictReader(io.StringIO(textwrap.dedent(GENERAL_ROOM_DETAILS)))
    # Sea wall boat slips share this list but aren't rooms.
    return [room for room in reader if room["room_type"] != "boat"]


ROOMS = _load_rooms()


def _name(room: dict) -> str:
    return room["room_display_name"].lower()


def _description(room: dict) -> str:
    return room["room_type_description"].lower()


def _has_balcony(room: dict) -> bool:
    return "balcony" in f"{_name(room)} {_description(room)}".replace("no balcony", "")


def _has_gulf_view(room: dict) -> bool:
    return "gulf" in _name(room) or any(term in _description(room) for term in ("gulf view", "gulf front"))


def _has_bay_view(room: dict) -> bool:
    return (
        any(term in _name(room) for term in ("bay front", "bayfront", "waterfront"))
        or any(term in _description(room) for term in ("bay view", "bay front"))
    )


# Keys match the values of RoomFeature in app/agents/__init__.py.
FEATURE_CHECKS = {
    "sleeper_sofa": lambda room: "sleeper sofa" in _name(room),
    "king_bed": lambda room: "king" in _name(room),
    "queen_bed": lambda room: "queen" in _name(room),
    "double_bed": lambda room: "double" in _name(room),
    "balcony": _has_balcony,
    "gulf_view": _has_gulf_view,
    "bay_view": _has_bay_view,
    "water_view": lambda room: _has_gulf_view(room) or _has_bay_view(room),
    # "Bedroom Suite" only: other rooms that mention a bedroom just have a half wall partition.
    "separate_bedroom": lambda room: "bedroom suite" in _name(room),
    "full_kitchen": lambda room: "full kitchen" in _description(room),
}


def find_rooms_by_features(features: list[str], hotel_ids: list[str]) -> list[dict]:
    """Rooms at the given hotels that have every requested feature, in hotel_ids order."""
    return [
        room
        for hotel_id in hotel_ids
        for room in ROOMS
        if room["hotel_id"] == hotel_id and all(FEATURE_CHECKS[feature](room) for feature in features)
    ]
