from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict


class BrowserRemediation:
    """Track browser configuration changes with reversible restore support."""

    def __init__(self, browser_state_path: str | Path):
        self.browser_state_path = Path(browser_state_path)
        self.browser_state_path.parent.mkdir(parents=True, exist_ok=True)
        if not self.browser_state_path.exists():
            self.browser_state_path.write_text("{}", encoding="utf-8")
        self._backup_store = self.browser_state_path.parent / "browser_state_backup.json"

    def load_state(self) -> Dict[str, Any]:
        try:
            payload = json.loads(self.browser_state_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            payload = {}
        return payload if isinstance(payload, dict) else {}

    def capture_snapshot(self) -> Dict[str, Any]:
        current = self.load_state()
        self._backup_store.write_text(json.dumps(current, indent=2, sort_keys=True), encoding="utf-8")
        return {"before_state": current, "backup_path": str(self._backup_store)}

    def set_value(self, key: str, value: Any) -> Dict[str, Any]:
        state = self.load_state()
        self.capture_snapshot()
        state[key] = value
        self._write_state(state)
        return {"key": key, "status": "updated", "value": value}

    def restore_value(self, key: str) -> Dict[str, Any]:
        if self._backup_store.exists():
            backup = json.loads(self._backup_store.read_text(encoding="utf-8"))
            if isinstance(backup, dict) and key in backup:
                state = self.load_state()
                state[key] = backup[key]
                self._write_state(state)
                return {"key": key, "status": "restored", "value": backup[key]}

        state = self.load_state()
        if key not in state:
            return {"key": key, "status": "missing"}
        del state[key]
        self._write_state(state)
        return {"key": key, "status": "restored", "value": None}

    def _write_state(self, state: Dict[str, Any]) -> None:
        self.browser_state_path.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
