"""Data management handlers — list, drop, clone datasets."""
from typing import Optional

from ..session_store import SessionStore


async def _handle_list_datasets(
    _filter_type: Optional[str] = None,
) -> dict:
    """List all active datasets and results."""
    store = SessionStore()
    datasets = store.list_datasets()
    return {'datasets': datasets, 'count': len(datasets)}


async def _handle_drop_dataset(dataset_id: str) -> dict:
    """Remove a dataset/result and release memory."""
    store = SessionStore()

    dropped = (store.drop_dataset(dataset_id)
               or store.drop_cluster_result(dataset_id)
               or store.drop_feature_result(dataset_id))

    if dropped:
        return {'dropped': True, 'dataset_id': dataset_id}
    return {'error': f'No dataset or result found: {dataset_id}',
            'truncated': False}


async def _handle_clone_dataset(dataset_id: str) -> dict:
    """Shallow-clone a dataset."""
    store = SessionStore()
    new_id = store.clone_dataset(dataset_id)
    if new_id is None:
        return {'error': f'Dataset not found: {dataset_id}', 'truncated': False}
    return {'original_dataset_id': dataset_id, 'cloned_dataset_id': new_id}
