# Root conftest — profiling hooks for integration tests.
#
# Registers --profiling-output CLI option and writes a JSON timing report
# after the test session completes. The profiler fixture itself is defined
# in tests/integration/conftest.py (always available as a fallback) and
# optionally overridden by this plugin when it loads successfully.
from __future__ import annotations

import pytest

_profiler_instance = None
_DEFAULT_OUTPUT = "/tmp/profiling-report.json"


def pytest_addoption(parser: pytest.Parser) -> None:
    """Add --profiling-output CLI flag."""
    parser.addoption(
        "--profiling-output",
        action="store",
        default=_DEFAULT_OUTPUT,
        help=f"Path for the JSON profiling report (default: {_DEFAULT_OUTPUT})",
    )


@pytest.fixture(scope="session")
def profiler():
    """Session-scoped EndpointProfiler instance."""
    global _profiler_instance  # noqa: PLW0603
    try:
        from tests.integration.profiler import EndpointProfiler
        _profiler_instance = EndpointProfiler()
    except ImportError:
        # If profiler module unavailable, return a no-op object
        from unittest.mock import MagicMock
        _profiler_instance = MagicMock()
    return _profiler_instance


def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
    """Write profiling JSON report after all tests complete."""
    if _profiler_instance is None:
        return
    output_path = session.config.getoption("profiling_output", _DEFAULT_OUTPUT)
    try:
        if hasattr(_profiler_instance, "write_json"):
            _profiler_instance.write_json(output_path)
    except (OSError, TypeError):
        pass


def pytest_terminal_summary(
    terminalreporter: pytest.TerminalReporter,
    exitstatus: int,
    config: pytest.Config,
) -> None:
    """Print profiling summary at end of test session."""
    if _profiler_instance is None:
        return
    output_path = config.getoption("profiling_output", _DEFAULT_OUTPUT)
    try:
        if hasattr(_profiler_instance, "print_summary"):
            terminalreporter.section("Profiling Summary")
            _profiler_instance.print_summary()
            terminalreporter.write_line(f"JSON report written to: {output_path}")
    except (OSError, TypeError):
        pass
