# ==============================================================================
# FILE: 3_Source_Code/decyphr/analysis_plugins/p11_target_analysis/create_visualization.py
# ==============================================================================
# PURPOSE: Generates rich HTML content for Advanced Target Analysis, 
#          visualizing supervised insights using Antigravity UI.

import plotly.graph_objects as go
import pandas as pd
from typing import Dict, Any, Optional, List
from decyphr.utils.plotting import apply_antigravity_theme, get_theme_colors

# Get standard colors
THEME_COLORS = get_theme_colors()

# --- Antigravity Helper Functions ---

def _create_card(title: str, content: str, subtitle: str = "") -> str:
    """Wraps content in a standard Antigravity details-card."""
    if not content: return ""
    sub = f"<p style='color: var(--text-tertiary); font-size: 0.9em; margin-top: -10px; margin-bottom: 20px;'>{subtitle}</p>" if subtitle else ""
    return f"""
    <div class='details-card'>
        <h3>{title}</h3>
        {sub}
        {content}
    </div>
    """

def _create_table(headers: List[str], rows: List[List[Any]], overflow: bool = False) -> str:
    """Creates a standard transparent Antigravity table."""
    if not rows: return "<p style='color: var(--text-tertiary); font-style: italic;'>No relevant data.</p>"
    
    thead = "".join([f"<th>{h}</th>" for h in headers])
    tbody = ""
    for row in rows:
        tbody += "<tr>" + "".join([f"<td>{cell}</td>" for cell in row]) + "</tr>"
    
    wrapper_class = "table-responsive" if overflow else ""
    return f"""
    <div class='{wrapper_class}'>
        <table class='details-table'>
            <thead><tr>{thead}</tr></thead>
            <tbody>{tbody}</tbody>
        </table>
    </div>
    """

def create_visuals(analysis_results: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """
    Creates rich HTML content for target analysis.
    """
    print("     -> Generating details & visualizations for Advanced Target Analysis...")
    
    if "error" in analysis_results:
        return {"error": analysis_results["error"]}
    if not analysis_results or "message" in analysis_results:
        return {"message": "Target analysis was not performed."}

    all_details_html: List[str] = []
    all_visuals: List[go.Figure] = []

    try:
        # Extract Results
        problem_type = analysis_results.get("problem_type", "Unknown")
        importances = analysis_results.get("feature_importances", {})
        mi_scores = analysis_results.get("mi_scores", {})
        corrs = analysis_results.get("correlations", {})
        model_score = analysis_results.get("model_score", {})
        lift_data = analysis_results.get("lift_data", {})
        target_dist = analysis_results.get("target_dist", {})

        # --- 1. Model Performance Card ---
        score_val = model_score.get("value", 0)
        score_name = model_score.get("metric", "Score")
        
        summary_rows = [
            ["Problem Type", problem_type],
            [f"Baseline Model {score_name}", f"<strong>{score_val:.4f}</strong>"],
            ["Target Distribution", str(target_dist)[:100] + "..."] # Simplified for card
        ]
        all_details_html.append(_create_card("Target Analysis Overview", 
             _create_table(["Metric", "Result"], summary_rows),
             "Insights generated by training a baseline LightGBM model to predict the target."))

        # --- 2. Top Feature Importances (Bar Chart) ---
        if importances:
            feats = list(importances.keys())
            vals = list(importances.values())
            # Sort for plotting (top at top)
            sorted_indices = sorted(range(len(vals)), key=lambda k: vals[k])
            feats = [feats[i] for i in sorted_indices]
            vals = [vals[i] for i in sorted_indices]

            fig_imp = go.Figure(data=go.Bar(
                x=vals, y=feats, orientation='h', 
                marker_color=THEME_COLORS["primary_accent"]
            ))
            fig_imp = apply_antigravity_theme(fig_imp)
            fig_imp.update_layout(title="Top Feature Importance (LightGBM)", xaxis_title="Gain", yaxis_title="Feature", height=450)
            all_visuals.append(fig_imp)
            
            all_details_html.append(_create_card("Predictive Drivers", 
                 "<div class='plot-placeholder-target'></div>",
                 "Which features contribute most to predicting the target?"))

        # --- 3. Mutual Information Table ---
        if mi_scores:
            mi_rows = [[k, f"{v:.4f}"] for k, v in mi_scores.items()]
            all_details_html.append(_create_card("Non-Linear Relationships (Mutual Info)",
                 _create_table(["Feature", "MI Score"], mi_rows),
                 "Mutual Information captures any relationship (linear or non-linear) between feature and target."))

        # --- 4. Lift Chart (if Classification) ---
        if lift_data:
            deciles = list(lift_data.keys())
            lifts = list(lift_data.values())
            
            fig_lift = go.Figure(data=go.Bar(
                x=deciles, y=lifts, marker_color=THEME_COLORS["secondary_accent"]
            ))
            fig_lift = apply_antigravity_theme(fig_lift)
            fig_lift.update_layout(
                 title="Lift Chart (Deciles)", 
                 xaxis_title="Decile (Prob. Bucket)", 
                 yaxis_title="Lift (vs Random)",
                 shapes=[dict(type="line", x0=-0.5, x1=9.5, y0=1, y1=1, line=dict(color="white", dash="dash"))]
            )
            all_visuals.append(fig_lift)
            
            all_details_html.append(_create_card("Model Lift", 
                 "<div class='plot-placeholder-target'></div>",
                 "How much better is the model at identifying the target class compared to random guessing?"))

        final_html = f"<div class='details-grid' style='display: flex; flex-direction: column; gap: 24px;'>{''.join(all_details_html)}</div>"

        print("     ... Details and visualizations for Target Analysis complete.")
        return {
            "details_html": final_html,
            "visuals": all_visuals
        }

    except Exception as e:
        error_message = f"Failed during target visualization: {e}"
        print(f"     ... {error_message}")
        import traceback
        traceback.print_exc()
        return {"error": error_message}