"""Tests for scripts/clear-provenance (#3).

Exercises argument handling and the inert --dry-run path only — no real xattr
mutation, no network. (Actually removing com.apple.provenance is macOS-only and
has real side effects, so it is not exercised here.)
"""
import subprocess
import tempfile
import unittest
from pathlib import Path

REPO = Path(__file__).resolve().parent.parent
SCRIPT = REPO / "scripts" / "clear-provenance"


def run(*args):
    proc = subprocess.run(["bash", str(SCRIPT), *args],
                          capture_output=True, text=True, cwd=str(REPO))
    return proc.returncode, proc.stdout, proc.stderr


class TestClearProvenance(unittest.TestCase):

    def test_dry_run_defaults_to_repo_root(self):
        rc, out, _ = run("--dry-run")
        self.assertEqual(rc, 0)
        self.assertIn("would run: xattr -r -d com.apple.provenance", out)
        self.assertIn(str(REPO), out)

    def test_dry_run_explicit_path(self):
        with tempfile.TemporaryDirectory() as d:
            f = Path(d) / "x.py"
            f.write_text("print('hi')\n")
            rc, out, _ = run("--dry-run", str(f))
            self.assertEqual(rc, 0)
            self.assertIn(str(f), out)

    def test_missing_path_errors(self):
        rc, _, err = run("--dry-run", "/no/such/path-xyz")
        self.assertEqual(rc, 1)
        self.assertIn("no such path", err)

    def test_bad_flag_exit_2(self):
        rc, _, _ = run("--bogus")
        self.assertEqual(rc, 2)

    def test_too_many_args_exit_2(self):
        rc, _, _ = run("a", "b")
        self.assertEqual(rc, 2)

    def test_only_targets_provenance_attribute(self):
        # The command removes only com.apple.provenance, not all xattrs.
        rc, out, _ = run("--dry-run")
        self.assertIn("com.apple.provenance", out)
        self.assertNotIn("xattr -rc", out)   # not a blanket "clear all"
        self.assertNotIn("-c ", out)


if __name__ == "__main__":
    unittest.main()
