"""
Export file validation service following Single Responsibility Principle.
"""

from dataclasses import dataclass
from typing import List, Optional
import polars as pl


@dataclass
class ValidationResult:
    """Result of export validation."""
    is_valid: bool
    missing_columns: List[str]
    error_message: Optional[str] = None
    record_count: Optional[int] = None


class ExportValidator:
    """
    Single responsibility: Validate CloudZero export files.

    Validates schema, required columns, and data types for export processing.
    """

    # Required columns for dual operations (10 total)
    REQUIRED_COLUMNS = [
        "Cloud Provider",
        "Service",
        "Usage Family",
        "Resource Type",
        "Operation",
        "Usage Type",
        "Instance Type",  # Now required for Operation 1
        "Pricing Unit",
        "Real Cost",
        "Usage Amount"
    ]

    def validate_export_schema(self, export_df: pl.DataFrame) -> ValidationResult:
        """
        Validate export file has required schema for dual operations.

        Args:
            export_df: DataFrame to validate

        Returns:
            ValidationResult with validation status and details
        """
        try:
            # Check for missing required columns
            missing_columns = [
                col for col in self.REQUIRED_COLUMNS
                if col not in export_df.columns
            ]

            if missing_columns:
                return ValidationResult(
                    is_valid=False,
                    missing_columns=missing_columns,
                    error_message=f"Missing required columns: {missing_columns}"
                )

            # Check for empty DataFrame
            record_count = export_df.height
            if record_count == 0:
                return ValidationResult(
                    is_valid=False,
                    missing_columns=[],
                    error_message="Export file contains no data records",
                    record_count=0
                )

            # Validation passed
            return ValidationResult(
                is_valid=True,
                missing_columns=[],
                record_count=record_count
            )

        except Exception as e:
            return ValidationResult(
                is_valid=False,
                missing_columns=[],
                error_message=f"Export validation failed: {e}"
            )

    def validate_pricing_data(self, export_df: pl.DataFrame) -> int:
        """
        Count records with valid usage data for Operation 2.

        Records with usage have positive real_cost and usage_amount values.

        Args:
            export_df: DataFrame to analyze (can be normalized or raw)

        Returns:
            Count of records with valid usage data
        """
        try:
            # Try normalized column names first, then fall back to raw names
            if "pricing_unit" in export_df.columns:
                # Normalized columns
                valid_usage = export_df.filter(
                    (pl.col("pricing_unit").is_not_null()) &
                    (pl.col("pricing_unit") != "") &
                    (pl.col("real_cost") > 0) &
                    (pl.col("usage_amount") > 0)
                ).height
            else:
                # Raw column names
                valid_usage = export_df.filter(
                    (pl.col("Pricing Unit").is_not_null()) &
                    (pl.col("Pricing Unit") != "") &
                    (pl.col("Real Cost") > 0) &
                    (pl.col("Usage Amount") > 0)
                ).height

            return valid_usage

        except Exception:
            return 0