"""Tests for the CodingListView widget."""

import pytest
from textual.app import App, ComposeResult

from skilark_cli.tui.widgets.coding_list_view import CodingListView


MOCK_PROBLEMS = [
    {"id": "p1", "title": "Two Sum", "difficulty": 1, "solved": True},
    {"id": "p2", "title": "Container With Most Water", "difficulty": 2, "solved": True},
    {"id": "p3", "title": "Rotate Array", "difficulty": 2, "solved": False},
    {"id": "p4", "title": "Sliding Window Maximum", "difficulty": 3, "solved": False},
]


class ListApp(App):
    def __init__(self, problems=None, category="arrays"):
        super().__init__()
        self._problems = problems or []
        self._category = category

    def compose(self) -> ComposeResult:
        yield CodingListView(id="coding-list")

    def on_mount(self) -> None:
        view = self.query_one("#coding-list", CodingListView)
        view.load(self._category, self._problems)


@pytest.mark.asyncio
async def test_coding_list_mounts():
    """CodingListView mounts without error."""
    app = ListApp(problems=MOCK_PROBLEMS)
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        assert view is not None


@pytest.mark.asyncio
async def test_coding_list_loads_problems():
    """Problem list stores all problems after load()."""
    app = ListApp(problems=MOCK_PROBLEMS)
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        assert len(view.problems) == 4


@pytest.mark.asyncio
async def test_coding_list_stores_category():
    """Category name is stored after load()."""
    app = ListApp(problems=MOCK_PROBLEMS, category="arrays")
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        assert view.category == "arrays"


@pytest.mark.asyncio
async def test_coding_list_random_unsolved():
    """get_random_unsolved_id returns an unsolved problem ID."""
    app = ListApp(problems=MOCK_PROBLEMS)
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        pid = view.get_random_unsolved_id()
        assert pid in ("p3", "p4")


@pytest.mark.asyncio
async def test_coding_list_random_unsolved_all_solved():
    """get_random_unsolved_id returns None when all are solved."""
    solved = [{"id": "p1", "title": "Two Sum", "difficulty": 1, "solved": True}]
    app = ListApp(problems=solved)
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        assert view.get_random_unsolved_id() is None


@pytest.mark.asyncio
async def test_coding_list_empty():
    """CodingListView handles empty problem list."""
    app = ListApp(problems=[], category="empty")
    async with app.run_test() as pilot:
        view = app.query_one("#coding-list", CodingListView)
        assert view.problems == []
        assert view.category == "empty"
