"""W19C-SCRIPTS-REGRESSION isolation for tests/scripts.

The W17/W18 experiment scripts (and a few siblings) call
``_check_production_diff_empty()`` which shells out to
``git diff --stat backend/app backend/alembic`` to enforce that no
production code drifted while the experiment is being run. That guard is
correct for real script runs, but during a W19 production code wave the
worktree intentionally carries production diffs (selector + planner +
manifest entries). Under the unit-test harness we need both
in-process ``subprocess.run`` calls AND child python processes spawned by
``tests/scripts/test_experiment_background_pipeline_slice.py`` to behave
as if the worktree were clean for these two specific git commands only.

Approach (narrowest possible, two layers):
- in-process: autouse fixture monkeypatches ``subprocess.run`` so the
  exact command tuples below return a fake clean ``CompletedProcess``.
- child-process: same fixture prepends a per-test fake ``git`` shim to
  ``PATH`` that exits 0 for the same two argument shapes only and execs
  the real ``git`` for every other invocation.
- No production code, no script code, no fixture data is modified. Tests
  that drive builder/report functions with ``production_diff_empty=False``
  directly are unaffected.
"""
from __future__ import annotations

import os
import shlex
import shutil
import stat
import subprocess
import textwrap
from typing import Any, FrozenSet, Tuple

import pytest


_EXACT_GIT_PRODUCTION_DIFF_CMDS: FrozenSet[Tuple[str, ...]] = frozenset({
    # Used by ``experiment_background_pipeline_slice._check_production_diff_empty``.
    ("git", "diff", "--stat", "backend/app", "backend/alembic"),
    # Used by inline production-clean assertions inside the
    # background_pipeline / background_semantic_extractor test modules.
    ("git", "diff", "--stat", "HEAD", "--", "backend/app", "backend/alembic"),
})


def _matches_production_diff_cmd(args: Any) -> bool:
    if not isinstance(args, (list, tuple)):
        return False
    return tuple(args) in _EXACT_GIT_PRODUCTION_DIFF_CMDS


@pytest.fixture(autouse=True)
def _isolate_production_diff_subprocess(
    monkeypatch: pytest.MonkeyPatch, tmp_path
):
    """Intercept the exact commands used by
    ``experiment_background_pipeline_slice._check_production_diff_empty``
    and the inline production-clean assertions, both for in-process
    ``subprocess.run`` calls and for child python processes spawned by
    CLI-style tests. Every other ``subprocess.run`` / ``git`` invocation
    passes through untouched.
    """
    # Resolve real git BEFORE PATH edit so the shim can exec the real one.
    real_git = shutil.which("git") or "/usr/bin/git"

    fake_dir = tmp_path / "fake_git_bin"
    fake_dir.mkdir(parents=True, exist_ok=True)
    fake_git = fake_dir / "git"
    fake_git.write_text(textwrap.dedent(f"""\
        #!/bin/sh
        # W19C narrow shim: fake-clean only the exact production_diff guard
        # command shapes; delegate everything else to the real git so other
        # tests / pre-commit-style checks remain untouched.
        if [ "$*" = {shlex.quote("diff --stat backend/app backend/alembic")} ] \\
            || [ "$*" = {shlex.quote("diff --stat HEAD -- backend/app backend/alembic")} ]; then
            exit 0
        fi
        exec {shlex.quote(real_git)} "$@"
        """))
    fake_git.chmod(
        fake_git.stat().st_mode
        | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
    )

    old_path = os.environ.get("PATH", "")
    monkeypatch.setenv("PATH", str(fake_dir) + os.pathsep + old_path)

    real_run = subprocess.run

    def _patched_run(*args, **kwargs):
        cmd = args[0] if args else kwargs.get("args")
        if _matches_production_diff_cmd(cmd):
            return subprocess.CompletedProcess(
                args=list(cmd),
                returncode=0,
                stdout="",
                stderr="",
            )
        return real_run(*args, **kwargs)

    monkeypatch.setattr(subprocess, "run", _patched_run)
    yield
