"""Ensure tests default auth off unless a test patches settings (before config import is too late for that)."""

from __future__ import annotations

import asyncio
import os
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path

import pytest
from fastapi.testclient import TestClient

_test_auth_config = Path(os.environ.get("TEMP", "/tmp")) / "pygitweb-test-auth.json"
os.environ.setdefault("PYGITWEB_AUTH", "0")
os.environ.setdefault("PYGITWEB_AUTH_CONFIG", str(_test_auth_config))


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

	app.state.shutting_down = False
	app.state.shutdown_event = asyncio.Event()
	yield