import pandas as pd
from .correlation import get_correlation
from .importance import get_feature_importance
from .ai_explainer import explain_feature
from .visualizer import plot_correlation, plot_feature_importance






def analyze(file_path, target, show_graphs=False):
    df = pd.read_csv(file_path)

    if target not in df.columns:
        raise ValueError("Target column not found")

    X = df.drop(columns=[target])
    y = df[target]

    corr = get_correlation(df, target)
    importance = get_feature_importance(X, y)

    final_scores = {}

    for feature in X.columns:
        corr_val = abs(corr.get(feature, 0))
        imp_val = importance.get(feature, 0)

        final_scores[feature] = 0.5 * corr_val + 0.5 * imp_val

    ranked_features = sorted(final_scores.items(), key=lambda x: x[1], reverse=True)

    # AI explanations
    explanations = {}
    for feature, score in ranked_features:
        explanations[feature] = explain_feature(
            feature,
            round(corr.get(feature, 0), 3),
            round(importance.get(feature, 0), 3)
        )

    # ✅ Clean Output
    format_output(ranked_features, explanations)
    generate_summary(ranked_features)
        # Show graphs if enabled
    if show_graphs:
        plot_correlation(df)
        plot_feature_importance(ranked_features)








# def analyze(file_path, target):
#     df = pd.read_csv(file_path)

#     if target not in df.columns:
#         raise ValueError("Target column not found")

#     X = df.drop(columns=[target])
#     y = df[target]

#     corr = get_correlation(df, target)
#     importance = get_feature_importance(X, y)

#     final_scores = {}

#     for feature in X.columns:
#         corr_val = abs(corr.get(feature, 0))
#         imp_val = importance.get(feature, 0)

#         score = 0.5 * corr_val + 0.5 * imp_val
#         final_scores[feature] = score

#     sorted_features = sorted(final_scores.items(), key=lambda x: x[1], reverse=True)

#     # 🔥 AI explanations
#     explanations = {}

#     for feature, score in sorted_features:
#         explanations[feature] = explain_feature(
#             feature,
#             round(corr.get(feature, 0), 3),
#             round(importance.get(feature, 0), 3)
#         )

#     return df, sorted_features, explanations



def format_output(ranked_features, explanations):
    print("\n Feature Analysis Report\n")

    for feature, score in ranked_features:
        print(f"🔹 Feature: {feature}")
        print(f"   Score: {round(score, 3)}")
        print(f"   Insight: {explanations.get(feature, 'N/A')}")
        print("-" * 40)





def generate_summary(ranked_features):
    print("\n📌 Summary:\n")

    top_feature = ranked_features[0][0]
    print(f"✔ {top_feature} is the most important feature.")

    if len(ranked_features) > 1:
        print(f"✔ {ranked_features[1][0]} has moderate importance.")

    if len(ranked_features) > 2:
        print(f"✔ {ranked_features[-1][0]} has lower contribution.")