"""CSV cache handler."""

from pathlib import Path
from typing import Optional
import pandas as pd

from kline_package.cache.base import BaseCache


class CSVCache(BaseCache):
    """
    Cache handler for CSV format.
    
    CSV is a simple text-based format that provides:
    - Human-readable data
    - Easy inspection and editing
    - Wide compatibility with various tools
    """
    
    def __init__(self, cache_dir: str = "./cache"):
        """
        Initialize the CSV cache handler.
        
        Args:
            cache_dir: Directory where cache files will be stored
        """
        super().__init__(cache_dir)
        self.extension = ".csv"
    
    def save(
        self,
        data: pd.DataFrame,
        filename: str,
        index: bool = True
    ) -> None:
        """
        Save DataFrame to CSV file.
        
        Args:
            data: The DataFrame to save
            filename: The name of the file (without extension)
            index: Whether to save the index (default: True)
            
        Raises:
            ValueError: If data is empty or invalid
            IOError: If file cannot be written
        """
        if data is None or data.empty:
            raise ValueError("Cannot save empty DataFrame")
        
        file_path = self._get_file_path(filename)
        
        try:
            data.to_csv(file_path, index=index)
        except Exception as e:
            raise IOError(f"Failed to save CSV file: {e}")
    
    def load(
        self,
        filename: str,
        index_col: Optional[int] = 0
    ) -> pd.DataFrame:
        """
        Load DataFrame from CSV file.
        
        Args:
            filename: The name of the file to load (without extension)
            index_col: Column to use as index (default: 0, None for no index)
            
        Returns:
            pd.DataFrame: The loaded DataFrame
            
        Raises:
            FileNotFoundError: If file doesn't exist
            IOError: If file cannot be read
        """
        file_path = self._get_file_path(filename)
        
        if not file_path.exists():
            raise FileNotFoundError(f"CSV file not found: {file_path}")
        
        try:
            # Try to parse 'Open Time' as datetime if it exists
            df = pd.read_csv(file_path, index_col=index_col)
            if 'Open Time' in df.columns:
                df['Open Time'] = pd.to_datetime(df['Open Time'], utc=True)
            return df
        except Exception as e:
            raise IOError(f"Failed to load CSV file: {e}")
    
    def exists(self, filename: str) -> bool:
        """
        Check if a CSV cache file exists.
        
        Args:
            filename: The name of the file to check (without extension)
            
        Returns:
            bool: True if file exists, False otherwise
        """
        file_path = self._get_file_path(filename)
        return file_path.exists()
    
    def delete(self, filename: str) -> None:
        """
        Delete a CSV cache file.
        
        Args:
            filename: The name of the file to delete (without extension)
        """
        file_path = self._get_file_path(filename)
        if file_path.exists():
            file_path.unlink()
    
    def list_files(self) -> list:
        """
        List all CSV cache files.
        
        Returns:
            list: List of cache file names (without extensions)
        """
        csv_files = list(self.cache_dir.glob(f"*{self.extension}"))
        return [f.stem for f in csv_files]
    
    def _get_file_path(self, filename: str) -> Path:
        """Get full file path with extension."""
        if not filename.endswith(self.extension):
            filename = f"{filename}{self.extension}"
        return self.cache_dir / filename
