import json
import tempfile
import unittest
from pathlib import Path

from remediation.firewall import FirewallRemediation


class TestFirewallRemediation(unittest.TestCase):
    def test_set_and_restore_rule(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            firewall_path = root / "firewall_state.json"
            firewall_path.write_text(
                json.dumps({
                    "rules": {
                        "BlockSuspiciousProxy": {
                            "enabled": True,
                            "direction": "outbound",
                            "action": "block",
                        }
                    }
                }),
                encoding="utf-8",
            )

            firewall = FirewallRemediation(firewall_path)
            snapshot = firewall.capture_snapshot()
            self.assertIn("BlockSuspiciousProxy", snapshot["before_state"]["rules"])

            updated = firewall.set_rule("BlockSuspiciousProxy", enabled=False, direction="outbound", action="allow")
            self.assertEqual(updated["status"], "updated")
            self.assertFalse(firewall.load_state()["rules"]["BlockSuspiciousProxy"]["enabled"])

            restored = firewall.restore_rule("BlockSuspiciousProxy")
            self.assertEqual(restored["status"], "restored")
            self.assertTrue(firewall.load_state()["rules"]["BlockSuspiciousProxy"]["enabled"])

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

            firewall = FirewallRemediation(path)
            result = firewall.restore_rule("UnknownRule")
            self.assertEqual(result["status"], "missing")


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