"""Regression: staging must not pathspec-add deleted files after git rm."""

import subprocess
from pathlib import Path

import pytest


def _git(path: Path, *args: str) -> str:
    return subprocess.check_output(["git", "-C", str(path), *args], text=True).strip()


@pytest.mark.asyncio
async def test_stage_publishable_skips_missing_deleted_pathspecs(tmp_path):
    from src.workers.repo_ops import stage_publishable_and_assert

    repo = tmp_path / "repo"
    repo.mkdir()
    _git(repo, "init", "-b", "main")
    _git(repo, "config", "user.name", "Test")
    _git(repo, "config", "user.email", "test@example.com")
    (repo / "app.vue").write_text("<template>old</template>\n", encoding="utf-8")
    (repo / "index.html").write_text("old\n", encoding="utf-8")
    _git(repo, "add", ".")
    _git(repo, "commit", "-m", "seed")
    # Discovery replace: wipe tracked tree, copy a starter that drops app.vue.
    _git(repo, "rm", "-r", "--ignore-unmatch", "--", ".")
    (repo / "index.html").write_text("new\n", encoding="utf-8")
    (repo / "pages").mkdir()
    (repo / "pages" / "index.vue").write_text("<template>home</template>\n", encoding="utf-8")
    porcelain = _git(repo, "status", "--porcelain")
    assert "app.vue" in porcelain

    staged = await stage_publishable_and_assert(str(repo))
    assert "index.html" in staged
    assert "pages/index.vue" in staged
    # Deletion of the old allowlisted entry remains staged without a pathspec error.
    assert "app.vue" in staged
    cached = _git(repo, "diff", "--cached", "--name-only")
    assert "app.vue" in cached.splitlines()
