"""
Integration hook for normalization pipeline.

This module provides a simple entry point for the normalization pipeline
that can be used by other modules without coupling to AtomSQL or database operations.
"""

from typing import Union, Iterable, Dict, Any, Tuple, TextIO, List, Optional
from pathlib import Path

from atomingest.normalization.core import (
    NormalizationConfig,
    NormalizationReport,
    NormalizationStepConfig,
)
from atomingest.normalization.pipeline import NormalizationPipeline

# Import standard_steps to register them
import atomingest.normalization.standard_steps  # noqa: F401


def normalize_then_validate(
    source: Union[str, Path, TextIO, Iterable[str]],
    config: Optional[NormalizationConfig] = None,
    steps: Optional[List[NormalizationStepConfig]] = None,
    strict: bool = False,
) -> Tuple[List[Dict[str, Any]], NormalizationReport]:
    """
    Normalize and validate data from a source.

    This is the main integration entry point for the normalization pipeline.
    It runs the normalization process and returns the normalized rows along
    with a detailed report.

    Args:
        source: Data source - can be a file path, file handle, or iterable of lines
        config: NormalizationConfig object. If None, a default config will be created.
        steps: List of NormalizationStepConfig objects. Only used if config is None.
        strict: Enable strict mode (raise on warnings). Only used if config is None.

    Returns:
        Tuple of (normalized_rows, report):
            - normalized_rows: List of normalized data rows as dictionaries
            - report: NormalizationReport with metrics, warnings, and validation results

    Example:
        >>> from atomingest.normalization.integration import normalize_then_validate
        >>> from atomingest.normalization.core import NormalizationStepConfig
        >>>
        >>> steps = [
        ...     NormalizationStepConfig(step="RemoveBOMStep", config={}, enabled=True),
        ...     NormalizationStepConfig(step="TrimWhitespaceStep", config={}, enabled=True),
        ... ]
        >>>
        >>> rows, report = normalize_then_validate("data.csv", steps=steps)
        >>> print(f"Processed {report.rows_emitted} rows")
        >>> if report.warnings:
        ...     print(f"Warnings: {report.warnings}")
    """
    # Create default config if not provided
    if config is None:
        config = NormalizationConfig(
            strict=strict, steps=steps if steps is not None else []
        )

    # Create and run the pipeline
    pipeline = NormalizationPipeline(config=config)
    row_iterator, report = pipeline.run(source)

    # Consume the iterator to get all rows
    # This also triggers validation (e.g., row count validation)
    normalized_rows = list(row_iterator)

    return normalized_rows, report


def normalize_csv_file(
    file_path: Union[str, Path],
    steps: Optional[List[NormalizationStepConfig]] = None,
    strict: bool = False,
) -> Tuple[List[Dict[str, Any]], NormalizationReport]:
    """
    Convenience function to normalize a CSV file.

    Args:
        file_path: Path to the CSV file
        steps: List of normalization steps to apply
        strict: Enable strict mode (raise on warnings)

    Returns:
        Tuple of (normalized_rows, report)

    Example:
        >>> from atomingest.normalization.integration import normalize_csv_file
        >>> rows, report = normalize_csv_file("data.csv")
        >>> print(f"Processed {len(rows)} rows")
    """
    return normalize_then_validate(file_path, steps=steps, strict=strict)


def normalize_csv_string(
    csv_content: str,
    steps: Optional[List[NormalizationStepConfig]] = None,
    strict: bool = False,
) -> Tuple[List[Dict[str, Any]], NormalizationReport]:
    """
    Convenience function to normalize CSV content from a string.

    Args:
        csv_content: CSV content as a string
        steps: List of normalization steps to apply
        strict: Enable strict mode (raise on warnings)

    Returns:
        Tuple of (normalized_rows, report)

    Example:
        >>> from atomingest.normalization.integration import normalize_csv_string
        >>> csv_data = "id,name\\n1,Alice\\n2,Bob"
        >>> rows, report = normalize_csv_string(csv_data)
        >>> print(f"Processed {len(rows)} rows")
    """
    import io

    return normalize_then_validate(io.StringIO(csv_content), steps=steps, strict=strict)
