"""
Local storage implementation for NAND cell states and memory operations
using JSON file storage.
"""

import json
from dataclasses import dataclass, asdict
from typing import Dict, Any, Optional, List
import threading
import time
from pathlib import Path
from config import get_storage_path
import os

@dataclass
class CellState:
    cell_id: str
    block_id: int
    page_id: int
    value: int
    trapped_electrons: int
    wear_count: int
    retention_loss: float
    temperature: float
    voltage_level: float
    quantum_state: List[float]
    timestamp: float

class StorageManager:
    """Manages local storage operations using JSON file"""
    
    _instance = None
    _lock = threading.Lock()
    _data_lock = threading.Lock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._init_storage()
            return cls._instance

    def _init_storage(self):
        """Initialize local storage"""
        self.storage_path = get_storage_path()
        self._load_data()

    def _load_data(self):
        """Load data from JSON file"""
        self.data = {}
        if os.path.exists(self.storage_path):
            try:
                with open(self.storage_path, 'r') as f:
                    self.data = json.load(f)
            except json.JSONDecodeError:
                # If file is corrupted, start with empty data
                pass

    def _save_data(self):
        """Save data to JSON file"""
        with self._data_lock:
            with open(self.storage_path, 'w') as f:
                json.dump(self.data, f, indent=2)

    def store_cell_state(self, state: CellState):
        """Store cell state in local storage"""
        with self._data_lock:
            key = f"cell_{state.cell_id}"
            self.data[key] = asdict(state)
            self._save_data()

    def get_cell_state(self, cell_id: str) -> Optional[CellState]:
        """Retrieve cell state from local storage"""
        with self._data_lock:
            key = f"cell_{cell_id}"
            if key in self.data:
                return CellState(**self.data[key])
            return None

    def update_cell_state(self, cell_id: str, updates: Dict[str, Any]) -> bool:
        """Update specific fields of a cell state"""
        with self._data_lock:
            key = f"cell_{cell_id}"
            if key in self.data:
                self.data[key].update(updates)
                self._save_data()
                return True
            return False

    def delete_cell_state(self, cell_id: str) -> bool:
        """Delete cell state from storage"""
        with self._data_lock:
            key = f"cell_{cell_id}"
            if key in self.data:
                del self.data[key]
                self._save_data()
                return True
            return False

    def list_cells(self) -> List[str]:
        """List all cell IDs in storage"""
        return [k[5:] for k in self.data.keys() if k.startswith("cell_")]

    def clear_storage(self):
        """Clear all data from storage"""
        with self._data_lock:
            self.data = {}
            self._save_data()
