from semantic_models.exceptions import ValidationError
from semantic_models.resolution import SourceKey

MAX_SAMPLE_VALUE_LENGTH = 30


def fetch_column_values(source: SourceKey, column_name: str, limit: int) -> list[str]:
    try:
        import dataiku

        client = dataiku.api_client()
        project = client.get_default_project()
        sm = project.get_semantic_model(source.semantic_model_id)
        version = sm.get_version(source.version_id)
        result = version.get_basic_distinct_values_for_attribute(
            entity=source.entity_name,
            attribute=column_name,
            max_values=limit,
        )
        raw_values = (result or {}).get("values", []) or []
        values: list[str] = []
        for v in raw_values:
            if v is None:
                values.append("")
                continue
            str_val = str(v)
            if len(str_val) > MAX_SAMPLE_VALUE_LENGTH:
                str_val = str_val[:MAX_SAMPLE_VALUE_LENGTH] + "..."
            values.append(str_val)
        return values
    except Exception as e:
        raise ValidationError(str(e))
