"""Convenience wrapper functions for quality checks.

These functions provide a simple function-based API that wraps the
QualityCheck class. For more control, use QualityCheck directly.

Example::

    >>> from pycharter.quality.wrappers import check_quality, profile_data
    >>> report = check_quality(
    ...     contract={"schema": {"properties": {"name": {"type": "string"}}}},
    ...     data=[{"name": "Alice"}],
    ... )
    >>> profile = profile_data([{"name": "Alice", "age": 30}])
"""

from __future__ import annotations

import logging
from typing import Any, Callable

from pycharter.metadata_store import MetadataStoreClient
from pycharter.quality.check import QualityCheck
from pycharter.quality.models import QualityCheckOptions, QualityReport
from pycharter.quality.profiling import DataProfiler

logger = logging.getLogger(__name__)


def check_quality(
    contract: dict[str, Any] | str,
    data: list[dict[str, Any]] | str | Callable[[], Any],
    options: QualityCheckOptions | None = None,
) -> QualityReport:
    """Run a one-liner quality check against a contract file or dict.

    Args:
        contract: Contract dict or file path to a contract file.
        data: Data records, file path, or callable returning records.
        options: Quality check options. Defaults to
            ``QualityCheckOptions.basic()`` when *None*.

    Returns:
        QualityReport with scores, violations, and metadata.

    Raises:
        ValueError: If *data* is empty or *contract* is invalid.

    Example::

        >>> report = check_quality(
        ...     {"schema": {"properties": {"id": {"type": "integer"}}}},
        ...     [{"id": 1}, {"id": 2}],
        ... )
        >>> print(report.quality_score.overall_score)
    """
    if options is None:
        options = QualityCheckOptions.basic()

    qc = QualityCheck()
    return qc.run(contract=contract, data=data, options=options)


def check_quality_with_store(
    store: MetadataStoreClient,
    contract_name: str,
    contract_version: str,
    data: list[dict[str, Any]] | str | Callable[[], Any],
    options: QualityCheckOptions | None = None,
) -> QualityReport:
    """Run a one-liner quality check using a contract from the metadata store.

    Args:
        store: Connected MetadataStoreClient instance.
        contract_name: Name of the data contract in the store.
        contract_version: Version of the data contract.
        data: Data records, file path, or callable returning records.
        options: Quality check options. Defaults to
            ``QualityCheckOptions.basic()`` when *None*.

    Returns:
        QualityReport with scores, violations, and metadata.

    Raises:
        ValueError: If the contract cannot be found or *data* is invalid.
    """
    if options is None:
        options = QualityCheckOptions.basic()

    qc = QualityCheck(store=store)
    return qc.run(
        contract_name=contract_name,
        contract_version=contract_version,
        data=data,
        options=options,
    )


def profile_data(
    data: list[dict[str, Any]],
    fields: list[str] | None = None,
) -> dict[str, Any]:
    """Profile a dataset without running validation.

    Returns statistical summaries (completeness, distributions, etc.)
    for each field.

    Args:
        data: List of data records to profile.
        fields: Optional subset of field names to profile. Profiles all
            fields when *None*.

    Returns:
        Dict with ``record_count``, ``field_profiles``, and
        ``overall_stats`` keys.

    Example::

        >>> result = profile_data([{"name": "Alice", "age": 30}])
        >>> print(result["record_count"])
        1
    """
    profiler = DataProfiler()
    return profiler.profile(data, fields=fields)
