from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import pytest

from pygitweb_pytesthtml.report_embed import embed_pytest_html_report

_SAMPLE_DOC = """<!DOCTYPE html>
<html>
<head>
<title id="head-title">report.html</title>
<style type="text/css">body { color: red; }</style>
</head>
<body>
<h1 id="title">report.html</h1>
<p>Report generated</p>
<table id="environment"></table>
<table id="results-table">
<thead id="results-table-head"><tr><th>Result</th></tr></thead>
</table>
<footer><div id="data-container" data-jsonblob="{}"></div><script>void 0;</script></footer>
</body>
</html>
"""


def test_embed_strips_document_wrapper_and_style() -> None:
	out = embed_pytest_html_report(_SAMPLE_DOC)
	assert "<!doctype" not in out.lower()
	assert "<html" not in out.lower()
	assert "<style" not in out.lower()
	assert 'class="pytest-html-report"' in out
	assert "<h2 " in out and 'class="pytest-html-report__title"' in out
	assert "<h1 " not in out


def test_embed_adds_table_classes() -> None:
	out = embed_pytest_html_report(_SAMPLE_DOC)
	assert 'id="environment" class="table table-vcenter card-table"' in out
	assert 'id="results-table" class="table table-vcenter card-table"' in out


def test_embed_preserves_scripts_and_data() -> None:
	out = embed_pytest_html_report(_SAMPLE_DOC)
	assert 'id="data-container"' in out
	assert "<script>void 0;</script>" in out


def test_embed_idempotent_for_fragment() -> None:
	once = embed_pytest_html_report(_SAMPLE_DOC)
	twice = embed_pytest_html_report(once)
	assert once == twice


def test_embed_real_pytest_html_report(tmp_path: Path) -> None:
	(tmp_path / "test_ok.py").write_text("def test_ok() -> None:\n    assert True\n", encoding="utf-8")
	report = tmp_path / "report.html"
	subprocess.run(
		[
			sys.executable,
			"-m",
			"pytest",
			f"--html={report}",
			"--self-contained-html",
		],
		cwd=tmp_path,
		check=True,
	)
	full = report.read_text(encoding="utf-8")
	assert "<style" in full
	out = embed_pytest_html_report(full)
	assert "<style" not in out
	assert 'id="results-table" class="table' in out
	assert "data-jsonblob" in out