from .utils import safe_float

def filter_rows(data, column, operator, value, explain=False):
    result = []
    checked_rows = 0
    matched_rows = 0

    for row in data:
        checked_rows += 1
        cell = safe_float(row[column])

        if cell is None:
            continue

        if operator == ">" and cell > value:
            result.append(row)
            matched_rows += 1
        elif operator == "<" and cell < value:
            result.append(row)
            matched_rows += 1
        elif operator == "==" and cell == value:
            result.append(row)
            matched_rows += 1

    if not explain:
        return result

    return f"""
Step 1: Total rows checked → {checked_rows}
Step 2: Operator used → {column} {operator} {value}
Step 3: Rows matched condition → {matched_rows}
Step 4: Filtering logic applied using comparison operator
Final Result → {result}
"""


def sort_data(data, column, explain=False):
    sorted_data = sorted(data, key=lambda x: x[column])

    if not explain:
        return sorted_data

    return f"""
Step 1: Sorting performed on column → {column}
Step 2: Used Python built-in sorted() function
Step 3: Sorting key → lambda x: x['{column}']
Final Result → {sorted_data}
"""