from __future__ import annotations

import subprocess
from pathlib import Path
from types import TracebackType
from typing import Self

from fastapi import Request
from starlette.responses import Response

from pygitweb.api.action import Action
from pygitweb.config import settings
from pygitweb_pytesthtml.constants import PYTESTHTML_ACTION_NAME


class ActionPytestHtml(Action):
	"""
	ActionPytestHtml: Run pytest and render the results.
	"""

	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 action_name(self) -> str:
		return PYTESTHTML_ACTION_NAME

	def action(self, project: str, req: Request | None = None) -> Response | None:
		cwd = Path(settings.PROJECTROOT) / project
		subprocess.run(
			["pytest", "--html=.pygitweb/pytest_report.html", "--self-contained-html"],
			cwd=str(cwd),
		)
		return None