"""Tests for bus arrival and location tools."""

from __future__ import annotations

import pytest
import respx
from httpx import Response

from korea_transit_mcp_server.tools.bus import get_bus_arrival, get_bus_location

BUS_ARRIVAL_URL = "http://ws.bus.go.kr/api/rest/stationinfo/getStationByUid"
BUS_POSITION_URL = "http://ws.bus.go.kr/api/rest/buspos/getBusPosByRtid"


def _make_bus_xml(items_xml: str) -> str:
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<ServiceResult>
<comMsgHeader/>
<msgHeader>
<headerCd>0</headerCd>
<headerMsg>정상적으로 처리되었습니다.</headerMsg>
<itemCount>{items_xml.count('<itemList>')}</itemCount>
</msgHeader>
<msgBody>
{items_xml}
</msgBody>
</ServiceResult>"""


@respx.mock
@pytest.mark.asyncio
async def test_get_bus_arrival():
    xml = _make_bus_xml("""
    <itemList>
        <stNm>강남역</stNm>
        <rtNm>333</rtNm>
        <arrmsg1>3분후[1번째 전]</arrmsg1>
        <arrmsg2>8분후[3번째 전]</arrmsg2>
        <nxtStn>역삼역</nxtStn>
        <routeType>6</routeType>
    </itemList>
    <itemList>
        <stNm>강남역</stNm>
        <rtNm>145</rtNm>
        <arrmsg1>곧 도착</arrmsg1>
        <arrmsg2>12분후[5번째 전]</arrmsg2>
        <nxtStn>신논현역</nxtStn>
        <routeType>6</routeType>
    </itemList>
    """)
    respx.get(BUS_ARRIVAL_URL).mock(return_value=Response(200, text=xml))

    result = await get_bus_arrival("22009")
    assert "강남역" in result
    assert "333" in result
    assert "145" in result
    assert "3분후" in result
    assert "곧 도착" in result


@respx.mock
@pytest.mark.asyncio
async def test_get_bus_arrival_empty():
    xml = _make_bus_xml("")
    respx.get(BUS_ARRIVAL_URL).mock(return_value=Response(200, text=xml))

    result = await get_bus_arrival("99999")
    assert "도착 예정 버스가 없습니다" in result


@respx.mock
@pytest.mark.asyncio
async def test_get_bus_location():
    xml = _make_bus_xml("""
    <itemList>
        <plainNo>서울74사1234</plainNo>
        <stopNm>역삼역</stopNm>
        <congetion>3</congetion>
        <islastyn>0</islastyn>
    </itemList>
    """)
    respx.get(BUS_POSITION_URL).mock(return_value=Response(200, text=xml))

    result = await get_bus_location("100100118", "333")
    assert "333번" in result
    assert "1대 운행" in result
    assert "역삼역" in result
    assert "여유" in result


@respx.mock
@pytest.mark.asyncio
async def test_get_bus_location_empty():
    xml = _make_bus_xml("")
    respx.get(BUS_POSITION_URL).mock(return_value=Response(200, text=xml))

    result = await get_bus_location("000000000", "999")
    assert "운행 중인 버스가 없습니다" in result
