from __future__ import annotations

import re

_REPORT_ROOT_CLASS = "pytest-html-report"
_TITLE_H1 = re.compile(
	r'<h1\s+id="title"([^>]*)>(.*?)</h1>',
	re.IGNORECASE | re.DOTALL,
)


def _extract_body_inner(html: str) -> str:
	lower = html.lower()
	body_open = lower.find("<body")
	if body_open == -1:
		return html
	content_start = html.find(">", body_open)
	if content_start == -1:
		return html
	content_start += 1
	body_close = lower.rfind("</body>")
	if body_close == -1:
		return html[content_start:].strip()
	return html[content_start:body_close].strip()


def _demote_title_h1(body: str) -> str:
	return _TITLE_H1.sub(
		rf'<h2 class="{_REPORT_ROOT_CLASS}__title"\1>\2</h2>',
		body,
		count=1,
	)


def _add_table_classes(body: str) -> str:
	body = re.sub(
		r'<table\s+id="environment"',
		'<table id="environment" class="table table-vcenter card-table"',
		body,
		count=1,
		flags=re.IGNORECASE,
	)
	return re.sub(
		r'<table\s+id="results-table"',
		'<table id="results-table" class="table table-vcenter card-table"',
		body,
		count=1,
		flags=re.IGNORECASE,
	)


def embed_pytest_html_report(html: str) -> str:
	"""Turn a pytest-html full document into a PyGitWeb fragment (no embedded report CSS)."""
	stripped = html.strip()
	if not stripped:
		return stripped
	lower = stripped.lower()
	if not (lower.startswith("<!doctype") or lower.startswith("<html")):
		if _REPORT_ROOT_CLASS in stripped:
			return stripped
		return f'<div class="{_REPORT_ROOT_CLASS}">{stripped}</div>'
	body = _extract_body_inner(stripped)
	body = _demote_title_h1(body)
	body = _add_table_classes(body)
	return f'<div class="{_REPORT_ROOT_CLASS}">\n{body}\n</div>'