import json
import tempfile
import unittest
from pathlib import Path

from remediation.defender import DefenderRemediation


class TestDefenderRemediation(unittest.TestCase):
    def test_set_and_restore_setting(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            defender_path = root / "defender_state.json"
            defender_path.write_text(
                json.dumps({
                    "settings": {
                        "real_time_protection": True,
                        "cloud_protection": True,
                    }
                }),
                encoding="utf-8",
            )

            defender = DefenderRemediation(defender_path)
            snapshot = defender.capture_snapshot()
            self.assertTrue(snapshot["before_state"]["settings"]["real_time_protection"])

            updated = defender.set_setting("real_time_protection", False)
            self.assertEqual(updated["status"], "updated")
            self.assertFalse(defender.load_state()["settings"]["real_time_protection"])

            restored = defender.restore_setting("real_time_protection")
            self.assertEqual(restored["status"], "restored")
            self.assertTrue(defender.load_state()["settings"]["real_time_protection"])

    def test_missing_setting_reports_missing(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            path = Path(tmpdir) / "defender_state.json"
            path.write_text(json.dumps({"settings": {}}), encoding="utf-8")

            defender = DefenderRemediation(path)
            result = defender.restore_setting("cloud_protection")
            self.assertEqual(result["status"], "missing")


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