"""Pytest fixtures for pygitweb (test env vars are set in the repo-root conftest.py)."""

from __future__ import annotations

import asyncio
from collections.abc import Generator
from contextlib import contextmanager

import pytest
from fastapi.testclient import TestClient


def clear_client_cookies(client: TestClient) -> None:
	client.cookies.clear()


def set_client_session(client: TestClient, username: str) -> None:
	from pygitweb.auth import ACCESS_TOKEN_COOKIE_NAME
	from pygitweb.sessions import create_session

	client.cookies.set(ACCESS_TOKEN_COOKIE_NAME, create_session(username, auth_method="local"))


@contextmanager
def client_as_user(client: TestClient, username: str) -> Generator[None, None, None]:
	set_client_session(client, username)
	try:
		yield
	finally:
		clear_client_cookies(client)


@pytest.fixture(autouse=True)
def _reset_pygitweb_app_lifecycle_state() -> None:
	"""Starlette TestClient lifespan sets shutting_down on exit; httpx ASGITransport never runs lifespan.

	Stale state made long-poll tests see ``shutting_down`` and skip ``wait_for_changes``, so notify woke 0 waiters.
	"""
	from pygitweb.main import app
	from pygitweb.plugin_registry import PluginRegistry

	app.state.shutting_down = False
	app.state.shutdown_event = asyncio.Event()
	if not hasattr(app.state, "plugins"):
		plugins = PluginRegistry()
		plugins.load_all()
		app.state.plugins = plugins
	yield