from __future__ import annotations

import subprocess

from fastapi import Request
from starlette.responses import Response

from pygitweb.api.action import Action
from pygitweb_pytesthtml.constants import PYTESTHTML_ACTION_NAME
from pygitweb_pytesthtml.worktree import cleanup_pytest_run, prepare_pytest_run


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

	def action_name(self) -> str:
		return PYTESTHTML_ACTION_NAME

	def action(self, project: str, req: Request | None = None) -> Response | None:
		cwd, report = prepare_pytest_run(project)
		try:
			subprocess.run(
				["pytest", f"--html={report}", "--self-contained-html"],
				cwd=str(cwd),
			)
		finally:
			cleanup_pytest_run(project)
		return None