"""Replay one pinned linter against an isolated passing and failing input."""
import argparse
import json
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory


def run(arguments, directory):
    return subprocess.run(arguments, cwd=directory, text=True, capture_output=True, check=False)


def workflow(expression):
    return """name: Smoke test
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Print the event
        env:
          EVENT_NAME: ${{ """ + expression + """ }}
        run: echo "$EVENT_NAME"
"""


def verify(tool, executable, directory):
    if tool == "actionlint":
        version_args = ["-version"]
        expected_version = "1.7.12"
        # This fixture is about expressions. Optional shell and Python linters are disabled.
        args = ["-color=false", "-shellcheck=", "-pyflakes=", "workflow.yaml"]
        filename = "workflow.yaml"
        valid = workflow("github.event_name")
        invalid = workflow("githbu.event_name")
        markers = ["[expression]", "githbu"]
    else:
        version_args = ["--version"]
        expected_version = "ruff 0.14.0"
        args = ["check", "--isolated", "--no-cache", "--select", "F821", "example.py"]
        filename = "example.py"
        valid = "def double(number):\n    return number * 2\n"
        invalid = "def double(number):\n    return nummber * 2\n"
        markers = ["F821", "nummber"]
    version = run([executable, *version_args], directory)
    if version.returncode != 0 or version.stdout.splitlines()[:1] != [expected_version]:
        raise SystemExit(f"Required {tool} version: {expected_version}")
    observed = []
    for label, source, expected_status in [("clean", valid, 0), ("regressed", invalid, 1)]:
        (directory / filename).write_text(source, encoding="utf-8")
        result = run([executable, *args], directory)
        diagnostic = (result.stdout + result.stderr).strip()
        observed.append({"case": label, "exit": result.returncode, "diagnostic": diagnostic})
        if result.returncode != expected_status:
            raise SystemExit(f"{tool} {label}: expected exit {expected_status}, got {result.returncode}\n{diagnostic}")
        if label == "regressed" and not all(marker in diagnostic for marker in markers):
            raise SystemExit(f"Expected the matching rule and identifier in {tool} output:\n{diagnostic}")
    print(json.dumps({"tool": tool, "version": expected_version, "arguments": args, "observed": observed}, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("tool", choices=["actionlint", "ruff"])
    parser.add_argument("--bin", help="Absolute executable path or name on PATH")
    options = parser.parse_args()
    with TemporaryDirectory(prefix="lint-pair-") as tmp:
        verify(options.tool, options.bin or options.tool, Path(tmp))
