import json
import tempfile
import unittest
from pathlib import Path

from remediation.startup import StartupRemediation


class TestStartupRemediation(unittest.TestCase):
    def test_capture_snapshot_and_disable_entry(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            entries_path = root / "startup_entries.json"
            entries_path.write_text(
                json.dumps([
                    {
                        "name": "DemoStartup",
                        "command": r"C:\Tools\demo.exe",
                        "enabled": True,
                        "source": "StartupFolder",
                    }
                ]),
                encoding="utf-8",
            )

            startup = StartupRemediation(entries_path)
            snapshot = startup.capture_snapshot()
            self.assertEqual(len(snapshot["before_state"]), 1)

            result = startup.disable_entry("DemoStartup")
            self.assertEqual(result["status"], "disabled")
            self.assertFalse(startup.load_entries()["DemoStartup"]["enabled"])

    def test_restore_entry_from_backup(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            entries_path = root / "startup_entries.json"
            entries_path.write_text(
                json.dumps([
                    {"name": "DemoStartup", "command": r"C:\Tools\demo.exe", "enabled": True, "source": "StartupFolder"}
                ]),
                encoding="utf-8",
            )

            startup = StartupRemediation(entries_path)
            startup.disable_entry("DemoStartup")
            restored = startup.restore_entry("DemoStartup")
            self.assertEqual(restored["status"], "restored")
            self.assertTrue(startup.load_entries()["DemoStartup"]["enabled"])

    def test_missing_entry_reports_missing(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            entries_path = Path(tmpdir) / "startup_entries.json"
            entries_path.write_text(json.dumps([]), encoding="utf-8")

            startup = StartupRemediation(entries_path)
            result = startup.disable_entry("Ghost")
            self.assertEqual(result["status"], "missing")


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