from pathlib import Path
import os
import inspect
from dotenv import load_dotenv

load_dotenv()

pytest_plugins = [
    'fixtures.pages'
]

def pytest_sessionfinish(session, exitstatus):
    """Генерация Markdown файлов с группировкой по классам"""
    if session.config.getoption("--generate-md"):
        tests_by_file = {}

        for item in session.items:
            if not (hasattr(item, 'function') and item.function.__doc__):
                continue

            file_path = str(item.fspath)
            file_name = os.path.splitext(os.path.basename(file_path))[0]

            if file_name not in tests_by_file:
                tests_by_file[file_name] = {}

            # Группируем тесты по классам
            class_name = item.cls.__name__ if hasattr(item, 'cls') else "Без класса"
            if class_name not in tests_by_file[file_name]:
                tests_by_file[file_name][class_name] = {
                    'doc': inspect.cleandoc(item.cls.__doc__) if hasattr(item, 'cls') and item.cls.__doc__ else "",
                    'tests': []
                }
            tests_by_file[file_name][class_name]['tests'].append(item)

        # Создаем директорию docs
        output_dir = Path("docs")
        output_dir.mkdir(exist_ok=True)

        # Генерируем файлы
        for file_name, classes in tests_by_file.items():
            md_content = f"# Документация тестов ({file_name}.py)\n\n"

            for class_name, class_data in classes.items():
                if class_name != "Без класса":
                    md_content += f"## Класс: {class_name}\n"
                    if class_data['doc']:
                        md_content += f"{class_data['doc']}\n\n"

                for item in class_data['tests']:
                    md_content += f"### {item.name}\n"
                    md_content += f"**Маркеры:** {', '.join(mark.name for mark in item.own_markers)}\n\n"
                    md_content += f"```python\n{inspect.cleandoc(item.function.__doc__)}\n```\n\n"

            output_file = output_dir / f"{file_name}.md"
            output_file.write_text(md_content, encoding='utf-8')

def pytest_addoption(parser):
    parser.addoption(
        "--generate-md",
        action="store_true",
        default=False,
        help="Генерировать Markdown документацию с группировкой по классам"
    )
