from __future__ import annotations

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


class StartupRemediation:
    """Track, disable, and restore startup entries with a reversible backup model."""

    def __init__(self, entries_path: str | Path):
        self.entries_path = Path(entries_path)
        self.entries_path.parent.mkdir(parents=True, exist_ok=True)
        if not self.entries_path.exists():
            self.entries_path.write_text("[]", encoding="utf-8")
        self._backup_store = self.entries_path.parent / "startup_backup.json"

    def load_entries(self) -> Dict[str, Dict[str, Any]]:
        try:
            payload = json.loads(self.entries_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            payload = []
        entries = {}
        for item in payload:
            name = str(item.get("name") or "unknown")
            entries[name] = item
        return entries

    def capture_snapshot(self) -> Dict[str, Any]:
        current = self.load_entries()
        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 disable_entry(self, name: str) -> Dict[str, Any]:
        entries = self.load_entries()
        if name not in entries:
            return {"name": name, "status": "missing"}

        self.capture_snapshot()
        current = entries[name]
        current["enabled"] = False
        self._write_entries(list(entries.values()))
        return {"name": name, "status": "disabled", "before": current}

    def restore_entry(self, name: 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 name in backup:
                entries = self.load_entries()
                entries[name] = backup[name]
                self._write_entries(list(entries.values()))
                return {"name": name, "status": "restored", "after": backup[name]}

        entries = self.load_entries()
        if name not in entries:
            return {"name": name, "status": "missing"}
        entries[name]["enabled"] = True
        self._write_entries(list(entries.values()))
        return {"name": name, "status": "restored", "after": entries[name]}

    def _write_entries(self, entries: List[Dict[str, Any]]) -> None:
        self.entries_path.write_text(json.dumps(entries, indent=2, sort_keys=True), encoding="utf-8")
