from __future__ import annotations

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


class RecoveryCenter:
    """Lightweight local recovery view for backup and restore operations.

    This keeps the project aligned with a transparent, auditable remediation model:
    items are listed, tracked, and summarized without silently mutating system state.
    """

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

    def load_items(self) -> List[Dict[str, Any]]:
        try:
            payload = json.loads(self._items_path.read_text(encoding="utf-8"))
        except (json.JSONDecodeError, OSError):
            payload = []
        return payload if isinstance(payload, list) else []

    def add_restore_item(self, *, name: str, item_type: str, path: str, status: str = "backed_up") -> Dict[str, Any]:
        items = self.load_items()
        item = {
            "name": name,
            "item_type": item_type,
            "path": path,
            "status": status,
            "restorable": status in {"backed_up", "restorable"},
        }
        items.append(item)
        self._items_path.write_text(json.dumps(items, indent=2, sort_keys=True), encoding="utf-8")
        return item

    def list_items(self) -> List[Dict[str, Any]]:
        return self.load_items()

    def summary(self) -> Dict[str, Any]:
        items = self.load_items()
        total = len(items)
        restorable_count = sum(1 for item in items if item.get("restorable"))
        return {
            "total_items": total,
            "restorable_count": restorable_count,
            "needs_review": total - restorable_count,
        }

    def render_summary(self) -> str:
        summary = self.summary()
        return (
            "Recovery Center\n"
            f"- Total items: {summary['total_items']}\n"
            f"- Restorable items: {summary['restorable_count']}\n"
            f"- Needs review: {summary['needs_review']}"
        )
