"""Station/stop search tools."""

from __future__ import annotations

from typing import Any

from korea_transit_mcp_server.clients import odsay

STATION_CLASS_NAMES = {
    0: "기타",
    1: "버스정류장",
    2: "지하철역",
    3: "기차역",
    4: "공항",
    5: "항구",
}


def _format_station_list(stations: list[dict[str, Any]], keyword: str) -> str:
    """Format a list of stations into readable text."""
    if not stations:
        return f"'{keyword}'에 대한 검색 결과가 없습니다."

    lines: list[str] = [f"'{keyword}' 검색 결과 ({len(stations)}건):"]
    for s in stations[:15]:
        name = s.get("stationName", "")
        sid = s.get("stationID", "")
        cls = int(s.get("stationClass", 0))
        cls_name = STATION_CLASS_NAMES.get(cls, "기타")
        x, y = s.get("x", ""), s.get("y", "")

        # Lane info
        lane_info = ""
        if "laneName" in s:
            lane_info = f" [{s['laneName']}]"
        elif "lane" in s and isinstance(s["lane"], list):
            lane_names = [ln.get("name", ln.get("busNo", "")) for ln in s["lane"][:5]]
            lane_info = f" [{', '.join(lane_names)}]"

        ars = ""
        if s.get("arsID") and s["arsID"] != "0":
            ars = f" (ARS: {s['arsID']})"

        lines.append(f"  {cls_name} | {name}{lane_info}{ars}")
        lines.append(f"    ID: {sid} | 좌표: {x}, {y}")

    if len(stations) > 15:
        lines.append(f"  ... 외 {len(stations) - 15}건")
    return "\n".join(lines)


async def search_station(keyword: str, station_type: str | None = None) -> str:
    """정류장 또는 역을 검색합니다.

    Args:
        keyword: 검색어 (e.g. "강남역", "판교역", "22009")
        station_type: "bus"=버스정류장만, "subway"=지하철역만, None=전체
    """
    station_class = None
    if station_type == "bus":
        station_class = 1
    elif station_type == "subway":
        station_class = 2

    data = await odsay.search_station(keyword, station_class)
    result = data.get("result", {})
    stations = result.get("station", [])
    return _format_station_list(stations, keyword)


async def find_nearby_stations(
    longitude: float,
    latitude: float,
    radius: int = 500,
) -> str:
    """현재 위치 주변의 정류장/역을 검색합니다.

    Args:
        longitude: 경도 (e.g. 127.027)
        latitude: 위도 (e.g. 37.498)
        radius: 검색 반경 (미터, 기본 500m)
    """
    data = await odsay.search_nearby_station(longitude, latitude, radius)
    result = data.get("result", {})
    stations = result.get("station", [])

    if not stations:
        return f"반경 {radius}m 내에 정류장/역이 없습니다."

    lines: list[str] = [f"📍 반경 {radius}m 내 정류장/역 ({len(stations)}건):"]
    for s in stations[:15]:
        name = s.get("stationName", "")
        cls = int(s.get("stationClass", 0))
        cls_name = STATION_CLASS_NAMES.get(cls, "기타")
        dist = s.get("distance", "")

        lane_info = ""
        if "laneName" in s:
            lane_info = f" [{s['laneName']}]"
        elif "lane" in s and isinstance(s["lane"], list):
            lane_names = [ln.get("name", ln.get("busNo", "")) for ln in s["lane"][:5]]
            lane_info = f" [{', '.join(lane_names)}]"

        ars = ""
        if s.get("arsID") and s["arsID"] != "0":
            ars = f" ARS:{s['arsID']}"

        lines.append(f"  {cls_name} | {name}{lane_info}{ars} — {dist}m")
        lines.append(f"    ID: {s.get('stationID', '')}")

    if len(stations) > 15:
        lines.append(f"  ... 외 {len(stations) - 15}건")

    return "\n".join(lines)
