from __future__ import annotations

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


class ScheduledTaskRemediation:
    """Model and reversible control for scheduled tasks."""

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

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

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

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

    def restore_task(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:
                tasks = self.load_tasks()
                tasks[name] = backup[name]
                self._write_tasks(list(tasks.values()))
                return {"name": name, "status": "restored", "after": backup[name]}

        tasks = self.load_tasks()
        if name not in tasks:
            return {"name": name, "status": "missing"}
        tasks[name]["enabled"] = True
        tasks[name]["state"] = "ready"
        self._write_tasks(list(tasks.values()))
        return {"name": name, "status": "restored", "after": tasks[name]}

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