import json
from pathlib import Path
from typing import List
from .block import Block


class LedgerStorage:
    def __init__(self, storage_dir: Path | None = None):
        if storage_dir:
            base_dir = storage_dir
        else:
            base_dir = Path.home() / ".altrus"
            base_dir.mkdir(exist_ok=True)

        self.path = base_dir / "ledger.json"

    def load(self) -> List[Block]:
        if not self.path.exists():
            return []

        try:
            with self.path.open("r") as f:
                raw = json.load(f)

            return [Block.from_dict(b) for b in raw]
        except (json.JSONDecodeError, ValueError, KeyError):
            return []

    def save(self, chain: List[Block]):
        import os
        temp_path = self.path.with_suffix(".tmp")
        with temp_path.open("w") as f:
            json.dump(
                [b.to_dict() for b in chain],
                f,
                indent=2,
            )
        os.replace(temp_path, self.path)
