from .utils import get_numeric_column

def mean(data, column, explain=False):
    values = get_numeric_column(data, column)
    total = sum(values)
    count = len(values)
    result = total / count

    if not explain:
        return result

    return f"""
Step 1: Extracted numeric values → {values}
Step 2: Sum of values → {total}
Step 3: Count of values → {count}
Step 4: Formula used → mean = sum / count
Step 5: Calculation → {total} / {count}
Final Result → {result}
"""


def median(data, column, explain=False):
    values = sorted(get_numeric_column(data, column))
    n = len(values)
    mid = n // 2

    if n % 2 == 0:
        result = (values[mid-1] + values[mid]) / 2
        formula = f"({values[mid-1]} + {values[mid]}) / 2"
    else:
        result = values[mid]
        formula = f"Middle value = {values[mid]}"

    if not explain:
        return result

    return f"""
Step 1: Sorted values → {values}
Step 2: Total elements → {n}
Step 3: Formula applied → {formula}
Final Result → {result}
"""


def minimum(data, column, explain=False):
    values = get_numeric_column(data, column)
    result = min(values)

    if not explain:
        return result

    return f"""
Step 1: Extracted numeric values → {values}
Step 2: Minimum value found using min()
Final Result → {result}
"""


def maximum(data, column, explain=False):
    values = get_numeric_column(data, column)
    result = max(values)

    if not explain:
        return result

    return f"""
Step 1: Extracted numeric values → {values}
Step 2: Maximum value found using max()
Final Result → {result}
"""


def variance(data, column, explain=False):
    values = get_numeric_column(data, column)
    m = sum(values) / len(values)
    squared_diff = [(x - m) ** 2 for x in values]
    result = sum(squared_diff) / len(values)

    if not explain:
        return result

    return f"""
Step 1: Values → {values}
Step 2: Mean → {m}
Step 3: Squared differences → {squared_diff}
Step 4: Formula → variance = Σ(x - mean)^2 / n
Final Result → {result}
"""


def std_dev(data, column, explain=False):
    var = variance(data, column)
    result = var ** 0.5

    if not explain:
        return result

    return f"""
Step 1: Variance calculated → {var}
Step 2: Formula → standard deviation = √variance
Step 3: Square root applied
Final Result → {result}
"""


def value_counts(data, column, explain=False):
    counts = {}
    for row in data:
        val = row[column]
        counts[val] = counts.get(val, 0) + 1

    if not explain:
        return counts

    return f"""
Step 1: Iterated through each row
Step 2: Counted occurrences using dictionary
Final Result → {counts}
"""