from __future__ import annotations

from collections.abc import Generator
from pathlib import Path
from unittest.mock import patch

import pygit2
import pytest
from fastapi.testclient import TestClient

from pygitweb.auth_config import AuthConfig, LocalUser
from pygitweb.config import settings
from pygitweb.main import app
from pygitweb.permissions import PermissionsMap


def _seed_repo(repo_dir: Path) -> None:
	pygit2.init_repository(str(repo_dir), bare=False)
	(repo_dir / "README.md").write_text("hello\n", encoding="utf-8")


@pytest.fixture
def hidden_projects_env(tmp_path: Path) -> Generator[dict[str, str], None, None]:
	root = tmp_path / "project-list"
	repo_dir = root / "alpha"
	repo_dir.mkdir(parents=True)
	_seed_repo(repo_dir)
	auth = AuthConfig(
		auth_mode="local",
		local_users=[LocalUser(user="admin", password="secret")],
		oauth_permissions=PermissionsMap.model_validate({"*": []}),
	)
	with (
		patch.object(settings, "PROJECTROOT", str(root)),
		patch.object(settings, "PROJECTS_LIST", str(root)),
		patch.object(settings, "PROJECT_MAXDEPTH", 2),
		patch.object(settings, "STRICT_EXPORT", False),
		patch.object(settings, "EXPORT_OK", ""),
		patch.object(settings, "LIST_ALL", True),
		patch.object(settings, "AUTH", True),
		patch("pygitweb.auth_config.auth_config", auth),
		patch("pygitweb.auth.auth_config", auth),
		patch("pygitweb.main.auth_config", auth),
	):
		yield {"root": str(root)}


def test_home_page_shows_auth_visibility_notice_when_no_readable_projects(
	hidden_projects_env: dict[str, str],
) -> None:
	del hidden_projects_env
	client = TestClient(app)
	resp = client.get("/")
	assert resp.status_code == 200
	assert "No projects are visible with your current authentication" in resp.text
	assert "<table" in resp.text