import pandas as pd
import re
import numpy as np

def to_camel_case(text: str) -> str:
    # Replace all non-alphanumeric characters (like -, _, etc.) with space
    cleaned = re.sub(r'[^a-zA-Z0-9]+', ' ', text)
    parts = cleaned.strip().split()
    if not parts:
        return ''
    # Make first word lowercase
    first_word = parts[0].lower()
    
    # Capitalize first letter of other words
    capitalized_rest = [word.capitalize() for word in parts[1:]]
    
    # Join all words with spaces to keep separation
    return ' '.join([first_word] + capitalized_rest)


# Build merge key from DataFrame rows (for tracking)
def make_merge_key(row):
    print("make_merge_key",row)
    return f"{row['general_ledger_code']}|{row['account_name']}|{row['category']}|{pd.to_datetime(row['date'])}|{row['debit']:.2f}|{row['credit']:.2f}"

def clean_df_for_json(df: pd.DataFrame) -> list:
    df = df.replace([np.inf, -np.inf], np.nan)
    df = df.where(pd.notnull(df), None)

    # Optional: Convert datetime columns to ISO strings
    for col in df.select_dtypes(include=["datetime64[ns]", "datetime64[ns, UTC]"]).columns:
        df[col] = df[col].astype(str)

    return df.to_dict(orient="records")


def safe_eval_formula(formula: str, context: dict) -> float:
    try:
        return eval(formula, {"__builtins__": {}}, context)
    except Exception:
        return 0.0
    



import hashlib

def make_row_hash(row):
    normalized = (
        str(row["general_ledger_code"]).strip(),
        str(row["account_name"]).strip().lower(),
        #str(row["category"]).strip().lower(),
        pd.to_datetime(row["date"]).strftime("%Y-%m-%d"),
        f"{float(row['debit']):.2f}",
        f"{float(row['credit']):.2f}",
    )
    concat = "|".join(normalized)
    return hashlib.md5(concat.encode()).hexdigest()  # or sha256 for stronger hashing