# mypy: ignore-errors
"""Standalone subprocess script for benchmark execution with tracing.

This script is invoked as a subprocess by
``run_trace_benchmarks_in_subprocess`` in ``_subprocess_runners.py``.  It
runs pytest with tracing enabled to capture benchmark call traces.

Usage::

    python _benchmark_worker.py <benchmarks_root> <tests_root> <trace_file>

The tracing infrastructure lives in ``_benchmark_tracing`` (the
``codeflash_trace`` decorator) and ``_benchmark_plugin`` (the
``codeflash_benchmark_plugin`` pytest plugin), both added in stage 20.

This file must NOT be imported as a module.
"""

import sys
from pathlib import Path

from codeflash_python.benchmarking import _benchmark_plugin
from codeflash_python.benchmarking._benchmark_plugin import (
    codeflash_benchmark_plugin,
)
from codeflash_python.benchmarking._benchmark_tracing import codeflash_trace

benchmarks_root = sys.argv[1]
tests_root = sys.argv[2]
trace_file = sys.argv[3]
project_root = Path.cwd()

if __name__ == "__main__":
    import pytest

    orig_recursion_limit = sys.getrecursionlimit()
    sys.setrecursionlimit(orig_recursion_limit * 2)

    try:
        plugins = [_benchmark_plugin, codeflash_benchmark_plugin]
        pytest_args = [
            benchmarks_root,
            "--noconftest",
            "-p",
            "no:benchmark",
            "-p",
            "no:codspeed",
            "-p",
            "no:cov",
            "-p",
            "no:profiling",
            "-s",
            "-o",
            "addopts=",
        ]

        codeflash_benchmark_plugin.setup(trace_file, project_root)

        codeflash_trace.setup(trace_file)
        pytest_args.insert(1, "--codeflash-trace")

        exitcode = pytest.main(pytest_args, plugins=plugins)
    except Exception as e:
        print(f"Failed to collect tests: {e!s}", file=sys.stderr)
        exitcode = -1
    finally:
        sys.setrecursionlimit(orig_recursion_limit)

    sys.exit(exitcode)
