"""
FastAPI dependencies for shared request validation (exported repositories, etc.).
"""

from __future__ import annotations

from typing import Annotated, Any

from fastapi import Depends, Form, HTTPException, Query

from pygitweb.config import settings
from pygitweb.projects import git_get_projects_list, project_in_list
from pygitweb.validation import is_valid_project


def _visible_projects_list() -> list[dict[str, Any]]:
	return git_get_projects_list(
		filter_path="",
		paranoid=settings.STRICT_EXPORT,
		export_ok=settings.EXPORT_OK,
	)


def project_visible_in_list(project: str) -> bool:
	"""True if ``project`` appears in the same listing as the project picker."""
	return project_in_list(project, _visible_projects_list)


def require_valid_project(project: str) -> str:
	"""Reject empty or unknown project paths (export_ok, strict list, etc.)."""
	if not project or project == "":
		raise HTTPException(status_code=400, detail="Project needed")
	if not is_valid_project(
		project,
		settings.PROJECTROOT,
		settings.EXPORT_OK,
		settings.STRICT_EXPORT,
		project_visible_in_list,
	):
		raise HTTPException(status_code=404, detail="No such project")
	return project


def require_valid_project_name(name: str) -> str:
	"""Same as ``require_valid_project`` for a path parameter named ``name``."""
	return require_valid_project(name)


def require_valid_project_from_query(
	project: Annotated[str, Query(..., description="Project path")],
) -> str:
	return require_valid_project(project)


def require_valid_project_form(project: Annotated[str, Form()]) -> str:
	return require_valid_project(project)


def require_notify_project(
	project: Annotated[str | None, Query(alias="project", description="Repository path")] = None,
) -> str:
	"""Internal notify: project must appear in the visible list (hook / long-poll contract)."""
	if not project or not project.strip():
		raise HTTPException(status_code=400, detail="project query parameter required")
	p = project.strip()
	if not project_visible_in_list(p):
		raise HTTPException(status_code=404, detail="No such project")
	return p


def board_create_resolved_project(
	p: Annotated[str | None, Query(alias="p")] = None,
	project: Annotated[str | None, Query(alias="project")] = None,
) -> str:
	"""Resolve ``?p=`` / ``?project=`` then validate as a normal project path."""
	chosen = (project or p or "").strip()
	if not chosen:
		raise HTTPException(status_code=400, detail="Project needed (use ?project= or ?p=)")
	return require_valid_project(chosen)


ValidatedPathProject = Annotated[str, Depends(require_valid_project)]
ValidatedQueryProject = Annotated[str, Depends(require_valid_project_from_query)]
ValidatedSettingsProject = Annotated[str, Depends(require_valid_project_name)]
ValidatedBoardCreateProject = Annotated[str, Depends(board_create_resolved_project)]
ValidatedNotifyProject = Annotated[str, Depends(require_notify_project)]
ValidatedFormProject = Annotated[str, Depends(require_valid_project_form)]