"""Compare test runtimes against a baseline commit using ``pytest-perf``.

This evaluator executes pytest with the ``--control`` option to compare the
current workspace against a baseline Git commit. The JSON report generated by
``pytest-perf`` is parsed to extract the aggregated speedup ratio. A value above
``1.0`` indicates the workspace is faster than the baseline. The speedup is
stored in :attr:`Evaluator.last_result`.
"""

from __future__ import annotations

import json
import subprocess
from pathlib import Path
from typing import Any

from .base import Evaluator


class PytestPerfRegressionEvaluator(Evaluator):
    """Measure speedup versus a baseline commit using pytest-perf."""

    def __init__(self, baseline: str) -> None:
        super().__init__()
        self.baseline = baseline

    def run(self, workspace: Path, bench_cmd: str, runs: int = 1, **kw: Any) -> float:
        cmd = [
            "pytest",
            "--json-report",
            "--control",
            self.baseline,
        ]
        if bench_cmd:
            cmd.extend(bench_cmd.split())

        subprocess.run(cmd, cwd=workspace, check=False)

        report_path = workspace / ".report.json"
        speedup = 0.0
        if report_path.exists():
            data = json.loads(report_path.read_text())
            perf = data.get("perf", {})
            speedup = float(perf.get("speedup", 0.0))
            report_path.unlink()

        self.last_result = {"baseline": self.baseline, "speedup": speedup}
        return speedup
