import json
import tempfile
import unittest
from pathlib import Path

from remediation.browser import BrowserRemediation


class TestBrowserRemediation(unittest.TestCase):
    def test_restore_homepage_and_proxy(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            root = Path(tmpdir)
            browser_path = root / "browser_state.json"
            browser_path.write_text(
                json.dumps({
                    "homepage": "https://example.com",
                    "proxy": "http://proxy.local:8080",
                    "search_provider": "https://search.example.com",
                }),
                encoding="utf-8",
            )

            browser = BrowserRemediation(browser_path)
            snapshot = browser.capture_snapshot()
            self.assertEqual(snapshot["before_state"]["homepage"], "https://example.com")

            browser.set_value("homepage", "https://malicious.example")
            restored = browser.restore_value("homepage")
            self.assertEqual(restored["status"], "restored")
            self.assertEqual(browser.load_state()["homepage"], "https://example.com")

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

            browser = BrowserRemediation(path)
            result = browser.restore_value("proxy")
            self.assertEqual(result["status"], "missing")


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