from __future__ import annotations

from pathlib import Path
from types import TracebackType
from typing import Self
from urllib.parse import quote

from pygitweb.api.subpage import Subpage
from pygitweb.config import settings
from pygitweb_pytesthtml.constants import PYTESTHTML_ACTION_NAME


class SubpagePytestHtml(Subpage):
	"""
	SubpagePytestHtml: Render the latest Pytest results for a project.
	"""

	def __enter__(self) -> Self:
		return self

	def __exit__(
		self,
		exc_type: type[BaseException] | None,
		exc_value: BaseException | None,
		traceback: TracebackType | None,
	) -> bool | None:
		return None

	def subpage_name(self) -> str:
		return "pytesthtml"

	def link_name(self, project: str) -> str | None:
		return "Pytest Results"

	def subpage_html(self, project: str) -> str | None:
		report_path = Path(settings.PROJECTROOT) / project / ".pygitweb" / "pytest_report.html"
		if not report_path.is_file():
			return "<p>No pytest report found.</p>"
		return report_path.read_text(encoding="utf-8")

	def summary_value_suffix_html(self, project: str, project_enc: str) -> str | None:
		a = quote(PYTESTHTML_ACTION_NAME, safe="")
		return (
			f'<a class="btn btn-sm btn-primary ms-2" role="button" href="/project/{project_enc}?a={a}">Run pytest</a>'
		)