from typing import Optional, Any
import os
import pandas as pd

try:
    from huggingface_hub import hf_hub_download
    from datasets import load_dataset as hf_load_dataset
    HF_AVAILABLE = True
except ImportError:
    HF_AVAILABLE = False

class HuggingFaceIntegration:
    """
    Integration with Hugging Face Hub.
    """
    
    @staticmethod
    def is_available() -> bool:
        return HF_AVAILABLE

    @staticmethod
    def load_dataset(repo_id: str, split: str = "train", **kwargs) -> pd.DataFrame:
        """
        Load a dataset from Hugging Face Hub and convert to pandas.
        
        Args:
            repo_id: HF Repo ID (e.g. 'teyfikoz/ethnidata-v3')
            split: Split to load (default: 'train')
            **kwargs: Args passed to load_dataset
            
        Returns:
            pd.DataFrame
        """
        if not HF_AVAILABLE:
            raise ImportError(
                "Hugging Face integration requires 'datasets' and 'huggingface_hub'. "
                "Install with: pip install datasets huggingface_hub"
            )
        
        print(f"📥 Loading dataset '{repo_id}' from Hugging Face Hub...")
        ds = hf_load_dataset(repo_id, split=split, **kwargs)
        return ds.to_pandas()

    @staticmethod
    def push_to_hub(df: pd.DataFrame, repo_id: str, token: Optional[str] = None):
        """
        Push local dataframe to Hugging Face Hub.
        """
        if not HF_AVAILABLE:
             raise ImportError("Requires 'datasets' and 'huggingface_hub'.")
             
        from datasets import Dataset
        ds = Dataset.from_pandas(df)
        ds.push_to_hub(repo_id, token=token)
        print(f"✅ Pushed to {repo_id}")
