from __future__ import annotations

from collections.abc import Generator
from unittest.mock import AsyncMock, patch

import pytest
from fastapi.testclient import TestClient

from pygitweb.config import settings
from pygitweb.main import app
from pygitweb.plugin_loader import PLUGIN_ACTIONS, apply_plugin_reload
from pygitweb.plugin_loader_test import _fake_entry_points


@pytest.fixture
def client() -> Generator[TestClient, None, None]:
    with TestClient(app) as c:
        yield c


def test_plugins_page_lists_available(client: TestClient) -> None:
    with (
        patch.object(settings, "AUTH", False),
        patch("pygitweb.settings.list_available_plugins", return_value=["pygitweb_demo"]),
        patch.object(settings, "ENABLED_PLUGINS", []),
    ):
        r = client.get("/settings/pygitweb")
    assert r.status_code == 200
    assert b'name="plugin" value="pygitweb_demo"' in r.content
    assert b'id="plugin_pygitweb_demo"' in r.content
    assert b"checked" not in r.content.split(b'id="plugin_pygitweb_demo"')[1].split(b">")[0]


def test_plugins_submit_enables_and_reloads(client: TestClient) -> None:
    notify = AsyncMock(return_value=0)
    previous = list(settings.ENABLED_PLUGINS)
    try:
        settings.ENABLED_PLUGINS = []
        with (
            patch.object(settings, "AUTH", False),
            patch("pygitweb.plugin_loader._entry_points", side_effect=_fake_entry_points),
            patch("pygitweb.settings.list_available_plugins", return_value=["pygitweb_demo", "pygitweb_other"]),
            patch("pygitweb.settings.CHANGE_QUEUE.notify_all", notify),
        ):
            apply_plugin_reload()
            assert PLUGIN_ACTIONS == {}
            r = client.post(
                "/settings/pygitweb/plugins",
                data={"plugin": "pygitweb_demo"},
                follow_redirects=False,
            )
            assert r.status_code == 303
            assert settings.ENABLED_PLUGINS == ["pygitweb_demo"]
            assert set(PLUGIN_ACTIONS) == {"demo_action"}
            notify.assert_awaited_once()
    finally:
        settings.ENABLED_PLUGINS = previous
        apply_plugin_reload()