import hashlib
import json
from typing import Any, List, Union
import briefcase_ai as bf

def load(path: str, format: str = "auto") -> List[Any]:
    """
    Loads data and automatically registers bf.DataRef for every record.
    Supports HuggingFace, Local JSON/CSV.
    """
    data = []
    
    if path.startswith("huggingface:"):
        from datasets import load_dataset
        hf_path = path.replace("huggingface:", "")
        dataset = load_dataset(hf_path, split="train")
        for row in dataset:
            record = dict(row)
            # Automatic Lineage
            record["_bf_dataref"] = _generate_dataref(record, path)
            data.append(record)
            
    elif path.endswith(".json"):
        with open(path, "r") as f:
            raw = json.load(f)
            for item in raw:
                item["_bf_dataref"] = _generate_dataref(item, path)
                data.append(item)
                
    return data

def _generate_dataref(content: Any, uri: str):
    """Computes SHA-256 fingerprint of the record content."""
    from briefcase_ai import DataRef
    fingerprint = hashlib.sha256(str(content).encode()).hexdigest()
    return DataRef(uri=uri, fingerprint=fingerprint)
