import pandas as pd
import numpy as np

POSSIBLE_DATE_COLS = ["fecha", "fecha_completa", "dia", "día", "date"]

def normalize_columns(df):
    df = df.copy()
    df.columns = (
        df.columns.astype(str)
                  .str.strip()
                  .str.lower()
                  .str.replace(" ", "_")
                  .str.replace("-", "_")
                  .str.replace("/", "_")
    )
    return df

def detect_date_column(df):
    for c in df.columns:
        if c.lower() in POSSIBLE_DATE_COLS:
            return c
        if "fecha" in c.lower():
            return c
    return None

def parse_date(df, col):
    df = df.copy()
    df[col] = pd.to_datetime(df[col], errors="coerce", dayfirst=True)
    return df

def detect_percent_unit(series):
    s = pd.to_numeric(series, errors="coerce").dropna()
    if s.empty:
        return "other"

    if s.quantile(0.95) <= 1.1:
        return "proportion"
    if s.max() > 1.1:
        return "percent"
    return "other"

def preprocess_dataframe(df):
    df = normalize_columns(df)

    date_col = detect_date_column(df)
    if date_col:
        df = parse_date(df, date_col)

    units = {}
    for c in df.columns:
        if any(k in c for k in ["%", "porcentaje", "tasa", "nivel"]):
            units[c] = detect_percent_unit(df[c])
        else:
            units[c] = "other"

    # asegurar numéricos donde se pueda
    for c in df.columns:
        try:
            df[c] = pd.to_numeric(df[c], errors="ignore")
        except:
            pass

    return df

