"""Tests for scripts/dedash.py CLI.

All tests are token-less. Run with:
    pytest tests/test_dedash_cli.py -q
"""

import pathlib
import subprocess
import sys

ROOT = pathlib.Path(__file__).resolve().parents[1]
SCRIPTS = ROOT / "scripts"

PYTHON = str(ROOT / "bin" / "python3") if (ROOT / "bin" / "python3").exists() else sys.executable
DEDASH = str(SCRIPTS / "dedash.py")


class TestDedashCli:
    def test_fixes_file_in_place(self, tmp_path):
        p = tmp_path / "page.html"
        p.write_text("<h2>Key—Point</h2><p>Test—text.</p>", encoding="utf-8")
        proc = subprocess.run([PYTHON, DEDASH, str(p)], capture_output=True, text=True)
        assert proc.returncode == 0, proc.stderr
        content = p.read_text(encoding="utf-8")
        assert "—" not in content

    def test_check_exits_nonzero_when_dashes_present(self, tmp_path):
        p = tmp_path / "page.html"
        p.write_text("<p>A—B</p>", encoding="utf-8")
        proc = subprocess.run([PYTHON, DEDASH, "--check", str(p)], capture_output=True, text=True)
        assert proc.returncode == 1

    def test_check_exits_zero_when_clean(self, tmp_path):
        p = tmp_path / "page.html"
        p.write_text("<p>No dashes here.</p>", encoding="utf-8")
        proc = subprocess.run([PYTHON, DEDASH, "--check", str(p)], capture_output=True, text=True)
        assert proc.returncode == 0

    def test_check_does_not_modify_file(self, tmp_path):
        original = "<p>A—B</p>"
        p = tmp_path / "page.html"
        p.write_text(original, encoding="utf-8")
        subprocess.run([PYTHON, DEDASH, "--check", str(p)], capture_output=True, text=True)
        assert p.read_text(encoding="utf-8") == original

    def test_stdin_mode(self):
        html = "<p>A—B and C–D.</p>"
        proc = subprocess.run(
            [PYTHON, DEDASH, "--stdin"],
            input=html, capture_output=True, text=True,
        )
        assert proc.returncode == 0
        assert "—" not in proc.stdout
        assert "–" not in proc.stdout

    def test_multiple_files(self, tmp_path):
        p1 = tmp_path / "a.html"
        p2 = tmp_path / "b.html"
        p1.write_text("<p>A—B</p>", encoding="utf-8")
        p2.write_text("<p>C–D</p>", encoding="utf-8")
        proc = subprocess.run(
            [PYTHON, DEDASH, str(p1), str(p2)], capture_output=True, text=True
        )
        assert proc.returncode == 0
        assert "—" not in p1.read_text(encoding="utf-8")
        assert "–" not in p2.read_text(encoding="utf-8")

    def test_clean_file_no_modification(self, tmp_path):
        original = "<p>No dashes, just a hyphen-word.</p>"
        p = tmp_path / "page.html"
        p.write_text(original, encoding="utf-8")
        proc = subprocess.run([PYTHON, DEDASH, str(p)], capture_output=True, text=True)
        assert proc.returncode == 0
        assert p.read_text(encoding="utf-8") == original
