"""Data quality checks."""

from bilgeai.analyzer.models import QualityIssue


def check_empty_rows(rows: list[dict]) -> QualityIssue | None:
    """Check for empty or near-empty rows."""
    empty_indices = []
    for i, row in enumerate(rows):
        values = [str(v).strip() for v in row.values()]
        if all(not v for v in values):
            empty_indices.append(i)

    if empty_indices:
        return QualityIssue(
            issue_type="empty_row",
            severity="warning",
            message=f"Found {len(empty_indices)} empty row(s)",
            row_indices=empty_indices[:10],
            count=len(empty_indices),
        )
    return None


def check_duplicates(rows: list[dict]) -> QualityIssue | None:
    """Check for duplicate rows."""
    seen = {}
    duplicate_indices = []

    for i, row in enumerate(rows):
        key = str(sorted(row.items()))
        if key in seen:
            duplicate_indices.append(i)
        else:
            seen[key] = i

    if duplicate_indices:
        return QualityIssue(
            issue_type="duplicate",
            severity="warning",
            message=f"Found {len(duplicate_indices)} duplicate row(s)",
            row_indices=duplicate_indices[:10],
            count=len(duplicate_indices),
        )
    return None


def check_encoding_issues(rows: list[dict]) -> QualityIssue | None:
    """Check for encoding issues (replacement characters, etc.)."""
    bad_indices = []

    for i, row in enumerate(rows):
        text = " ".join(str(v) for v in row.values())
        if "\ufffd" in text:  # Unicode replacement character
            bad_indices.append(i)

    if bad_indices:
        return QualityIssue(
            issue_type="encoding_error",
            severity="warning",
            message=f"Found {len(bad_indices)} row(s) with encoding issues",
            row_indices=bad_indices[:10],
            count=len(bad_indices),
        )
    return None


def run_quality_checks(rows: list[dict]) -> list[QualityIssue]:
    """Run all quality checks and return findings."""
    issues = []
    for check_fn in [check_empty_rows, check_duplicates, check_encoding_issues]:
        result = check_fn(rows)
        if result:
            issues.append(result)
    return issues
