import json
from pathlib import Path

import pytest

# Enable access to the built-in 'pytester' fixture
pytest_plugins = ("pytester",)
@pytest.mark.unit
def test_plugin_writes_artifacts(pytester):
    # Make the project root importable so '-p conftest_plugin' works inside pytester
    project_root = Path(__file__).resolve().parents[2]
    pytester.syspathinsert(str(project_root))
    # Create a minimal test file that includes a rich docstring
    pytester.makepyfile(
        test_sample='''
import pytest

@pytest.mark.req_001
def test_docstring_metadata():
    """
    Title: Example Test

    Description:
        Small sample to exercise the reporting plugin.

    Requirements: REQ-001

    Test Steps:
        1. do it

    Expected Result:
        - done
    """
    assert True
'''
    )

    # Run pytest in the temporary test environment, loading our reporting plugin
    result = pytester.runpytest(
        "-q",
        "-p",
        "conftest_plugin",
        "--html=reports/report.html",
        "--self-contained-html",
        "--junitxml=reports/junit.xml",
    )
    result.assert_outcomes(passed=1)

    # Check for the JSON coverage artifact
    cov = pytester.path / "reports" / "requirements_coverage.json"
    assert cov.is_file()
    data = json.loads(cov.read_text())

    # Validate REQ mapping and presence of artifacts
    assert "REQ-001" in data["requirements"]
    assert data["files"]["html"].endswith("report.html")
    assert data["files"]["junit"].endswith("junit.xml")

    # Check that the CI summary exists
    summary = pytester.path / "reports" / "summary.md"
    assert summary.is_file()
