import pytest
from unittest.mock import AsyncMock
from app.screener.ai_news import scraper


SAMPLE_HTML = """
<html><body>
<table class="type5"><tbody>
<tr><td class="title"><a href="/news1">삼성전자, HBM 양산 가시화</a></td><td class="date">2026.05.13 07:30</td></tr>
<tr><td class="title"><a href="/news2">삼성, 4분기 어닝 쇼크 우려</a></td><td class="date">2026.05.13 06:00</td></tr>
<tr><td class="title"><a href="/news3">메모리 시장 회복세</a></td><td class="date">2026.05.12 18:00</td></tr>
</tbody></table>
</body></html>
"""

EMPTY_HTML = "<html><body><table class='type5'><tbody></tbody></table></body></html>"


def _mk_client(status_code=200, text=SAMPLE_HTML):
    client = AsyncMock()
    resp = AsyncMock()
    resp.status_code = status_code
    resp.text = text
    client.get = AsyncMock(return_value=resp)
    return client


@pytest.mark.asyncio
async def test_fetch_news_success_returns_n_items():
    client = _mk_client()
    out = await scraper.fetch_news(client, "005930", n=2)
    assert len(out) == 2
    assert out[0]["title"] == "삼성전자, HBM 양산 가시화"
    assert out[0]["date"] == "2026.05.13 07:30"


@pytest.mark.asyncio
async def test_fetch_news_404_returns_empty():
    client = _mk_client(status_code=404, text="")
    out = await scraper.fetch_news(client, "999999", n=5)
    assert out == []


@pytest.mark.asyncio
async def test_fetch_news_empty_table_returns_empty():
    client = _mk_client(text=EMPTY_HTML)
    out = await scraper.fetch_news(client, "005930", n=5)
    assert out == []


@pytest.mark.asyncio
async def test_fetch_news_n_caps_results():
    client = _mk_client()
    out = await scraper.fetch_news(client, "005930", n=2)
    assert len(out) == 2  # 샘플에 3개 있지만 n=2로 잘림
