"""
Data quality scanner.
"""

import pandas as pd
import polars as pl

from app.core.logging import get_logger
from app.domain.models.dataset import DataQualityMetrics

logger = get_logger(__name__)


class QualityScanner:
    """Scan datasets for quality metrics."""

    def __init__(self):
        """Initialize scanner."""
        self.logger = logger

    def scan(self, df: pd.DataFrame | pl.DataFrame) -> DataQualityMetrics:
        """Scan dataset for quality metrics."""
        # Convert to pandas for scanning if needed
        if isinstance(df, pl.DataFrame):
            df_pandas = df.to_pandas()
        else:
            df_pandas = df

        total_rows = len(df_pandas)
        total_columns = len(df_pandas.columns)

        # Missing values analysis
        missing_values = {}
        missing_percentage = {}
        for col in df_pandas.columns:
            null_count = int(df_pandas[col].isna().sum())
            missing_values[col] = null_count
            missing_percentage[col] = (null_count / total_rows * 100) if total_rows > 0 else 0

        # Duplicate rows
        duplicate_rows = int(df_pandas.duplicated().sum())

        # Unique values count
        unique_values = {}
        for col in df_pandas.columns:
            unique_values[col] = int(df_pandas[col].nunique())

        # Column types
        column_types = {col: str(dtype) for col, dtype in df_pandas.dtypes.items()}

        # Memory usage
        memory_usage_mb = df_pandas.memory_usage(deep=True).sum() / (1024 * 1024)

        return DataQualityMetrics(
            total_rows=total_rows,
            total_columns=total_columns,
            missing_values=missing_values,
            missing_percentage=missing_percentage,
            duplicate_rows=duplicate_rows,
            unique_values=unique_values,
            column_types=column_types,
            memory_usage_mb=round(memory_usage_mb, 2),
        )
