# Copyright (c) CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com
#

from typing import Any

from src.utils.files import _read_csv_file, validate_decimal


def read_anomaly_csv_file_to_dict(
    file_path: str,
) -> tuple[list[dict[str, Any]], int, int, dict[int, list[dict[str, Any]]]]:
    """
    Read an anomaly CSV file and convert to a list of dictionaries with validation.

    Args:
        file_path: Path to the CSV file

    Returns:
        Tuple containing:
        - List of anomaly dictionaries
        - Total number of rows
        - Number of filtered rows
        - Validation errors by row number

    Raises:
        ValueError: If CSV format is invalid
    """
    # Load CSV data
    rows = _read_csv_file(file_path)

    # Fields that should be Decimal type
    decimal_fields = ["anomaly_cost"]

    # Track validation errors
    validation_errors = {}

    # Process rows and validate
    processed_rows = []
    for i, row in enumerate(rows, 1):  # 1-based for user-friendly row numbers
        # Skip completely empty rows
        if not any(val.strip() for val in row.values() if isinstance(val, str)):
            continue

        # Process each row
        processed_row = {}
        row_errors = []

        for key, value in row.items():
            # Skip empty keys
            if key is None or key.strip() == "":
                continue

            # Handle decimal fields
            if key in decimal_fields:
                decimal_value, is_valid, original = validate_decimal(value)
                processed_row[key] = decimal_value
                if not is_valid:
                    row_errors.append({"field": key, "original_value": original, "corrected_value": decimal_value})
            # Set send_notification flag
            elif key == "send_notification":
                # Convert to boolean (case-insensitive)
                if isinstance(value, str) and value.strip().lower() in ("true", "yes", "y", "1"):
                    processed_row[key] = True
                elif isinstance(value, str) and value.strip().lower() in ("false", "no", "n", "0"):
                    processed_row[key] = False
                else:
                    # Default is False if not explicitly set to True
                    processed_row[key] = False
                    if value is not None and value.strip() != "":
                        row_errors.append({"field": key, "original_value": value, "corrected_value": False})
            else:
                processed_row[key] = value

        # Add row to results
        processed_rows.append(processed_row)

        # Record validation errors
        if row_errors:
            validation_errors[i] = row_errors

    return processed_rows, len(rows), len(rows) - len(processed_rows), validation_errors
