"""
Phase 3: Deep Analysis - Comprehensive ITSM Analytics
Covers: SLA Performance, MTTR, Closure Code Analysis, Text Mining, AI/Automation Impact
"""

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from pathlib import Path
from datetime import datetime, timedelta
import warnings
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.metrics import classification_report, roc_auc_score, confusion_matrix
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from collections import Counter
import re
warnings.filterwarnings('ignore')

# Paths
OUTPUT_DIR = Path('/app/workspace/temp_files')
OUTPUT_DIR.mkdir(exist_ok=True)
IMG_DIR = Path('/app/workspace/assets/images')
IMG_DIR.mkdir(exist_ok=True)

# Load cleaned data
print("=" * 80)
print("PHASE 3: DEEP ANALYSIS - COMPREHENSIVE ITSM ANALYTICS")
print("=" * 80)

df_incident = pd.read_pickle(OUTPUT_DIR / 'incident_dump_cleaned.pkl')
df_service = pd.read_pickle(OUTPUT_DIR / 'service_tasks_cleaned.pkl')

# =============================================================================
# SECTION 1: SLA PERFORMANCE & MTTR DECOMPOSITION
# =============================================================================
print("\n[1] SLA PERFORMANCE & MTTR DECOMPOSITION...")

# SLA Targets (from requirements)
sla_targets = {1: 1, 2: 4, 3: 16, 4: 48}  # Critical, High, Moderate, Low in hours
sla_target_map = {'1 - Critical': 1, '2 - High': 4, '3 - Moderate': 16, '4 - Low': 48}

# Filter resolved incidents for MTTR analysis
resolved = df_incident[df_incident['Resolved_DT'].notna()].copy()
resolved['MTTR_Hours'] = (resolved['Resolved_DT'] - resolved['Opened_DT']).dt.total_seconds() / 3600

# MTTR Statistics by Priority
mttr_by_priority = resolved.groupby('Priority').agg({
    'MTTR_Hours': ['mean', 'median', 'std', 'min', 'max', 'count']
}).round(2)
mttr_by_priority.columns = ['Mean_MTTR', 'Median_MTTR', 'Std_MTTR', 'Min_MTTR', 'Max_MTTR', 'Count']

# SLA Compliance by Priority
resolved['SLA_Target'] = resolved['Priority'].map(sla_target_map)
resolved['SLA_Breached'] = resolved.apply(
    lambda x: 1 if pd.notna(x['SLA_Target']) and x['MTTR_Hours'] > x['SLA_Target'] else 0, axis=1
)
resolved['Within_SLA'] = resolved.apply(
    lambda x: 1 if pd.notna(x['SLA_Target']) and x['MTTR_Hours'] <= x['SLA_Target'] else 0, axis=1
)

sla_compliance = resolved.groupby('Priority').agg({
    'SLA_Breached': ['sum', 'mean'],
    'Within_SLA': ['sum', 'mean']
}).round(4)
sla_compliance.columns = ['Breaches', 'Breach_Rate', 'Met', 'Compliance_Rate']

# MTTR vs SLA Target Chart
fig_mttr = go.Figure()
priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low']
for priority in priorities:
    if priority in resolved['Priority'].values:
        data = resolved[resolved['Priority'] == priority]['MTTR_Hours']
        fig_mttr.add_trace(go.Box(
            y=data,
            name=priority,
            boxpoints='outliers',
            marker=dict(size=4),
            text=data.apply(lambda x: f'{x:.1f}h' if pd.notna(x) else '')
        ))

fig_mttr.add_hline(y=1, line_dash="dash", line_color="red", annotation_text="Critical SLA (1h)")
fig_mttr.add_hline(y=4, line_dash="dash", line_color="orange", annotation_text="High SLA (4h)")
fig_mttr.add_hline(y=16, line_dash="dash", line_color="yellow", annotation_text="Moderate SLA (16h)")
fig_mttr.add_hline(y=48, line_dash="dash", line_color="green", annotation_text="Low SLA (48h)")

fig_mttr.update_layout(
    title='MTTR Distribution by Priority vs SLA Targets',
    yaxis_title='MTTR (Hours)',
    template='plotly_white',
    height=500
)
fig_mttr.write_html(IMG_DIR / 'sla_mttr_by_priority.html')
fig_mttr.write_image(IMG_DIR / 'sla_mttr_by_priority.png', scale=2)
print("  Saved: sla_mttr_by_priority")

# SLA Compliance by Assignment Group (Top 15)
sla_by_group = resolved.groupby('Assignment_Group').agg({
    'SLA_Breached': ['sum', 'mean'],
    'Incident_Number': 'count'
}).reset_index()
sla_by_group.columns = ['Assignment_Group', 'Breaches', 'Breach_Rate', 'Total_Incidents']
sla_by_group = sla_by_group[sla_by_group['Total_Incidents'] >= 50].sort_values('Breach_Rate', ascending=False)

fig_sla_group = px.bar(
    sla_by_group.head(15),
    x='Breach_Rate',
    y='Assignment_Group',
    orientation='h',
    color='Breach_Rate',
    color_continuous_scale='RdYlGn_r',
    title='SLA Breach Rate by Assignment Group (Top 15 by Volume)',
    labels={'Breach_Rate': 'SLA Breach Rate', 'Assignment_Group': 'Assignment Group'}
)
fig_sla_group.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig_sla_group.write_html(IMG_DIR / 'sla_breach_by_group.html')
fig_sla_group.write_image(IMG_DIR / 'sla_breach_by_group.png', scale=2)
print("  Saved: sla_breach_by_group")

# =============================================================================
# SECTION 2: SLA BREACH PREDICTION MODEL
# =============================================================================
print("\n[2] BUILDING SLA BREACH PREDICTION MODEL...")

# Prepare features for prediction
model_df = resolved.copy()

# Create features
model_df['Hour_of_Day'] = model_df['Opened_DT'].dt.hour
model_df['Day_of_Week'] = model_df['Opened_DT'].dt.dayofweek
model_df['Month'] = model_df['Opened_DT'].dt.month
model_df['Is_Weekend'] = (model_df['Day_of_Week'] >= 5).astype(int)

# Assignment group load (incidents per group per day)
group_daily_load = model_df.groupby(['Assignment_Group', model_df['Opened_DT'].dt.date]).size().reset_index(name='Daily_Load')
model_df['Date_Only'] = model_df['Opened_DT'].dt.date
model_df = model_df.merge(group_daily_load, left_on=['Assignment_Group', 'Date_Only'], 
                          right_on=['Assignment_Group', 'Opened_DT'], how='left')

# Encode categorical variables
le_group = LabelEncoder()
le_channel = LabelEncoder()
le_region = LabelEncoder()

model_df['Assignment_Group_Encoded'] = le_group.fit_transform(model_df['Assignment_Group'].fillna('Unknown'))
model_df['Channel_Encoded'] = le_channel.fit_transform(model_df['Channel'].fillna('Unknown'))
model_df['Region_Encoded'] = le_region.fit_transform(model_df['Caller_Region'].fillna('Unknown'))

# Prepare features
feature_cols = ['Priority_Num', 'Hour_of_Day', 'Day_of_Week', 'Is_Weekend', 
                'Daily_Load', 'Assignment_Group_Encoded', 'Channel_Encoded', 'Region_Encoded']
model_df = model_df.dropna(subset=feature_cols + ['SLA_Breached'])

X = model_df[feature_cols]
y = model_df['SLA_Breached']

# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Train logistic regression
lr_model = LogisticRegression(max_iter=1000, class_weight='balanced', random_state=42)
lr_model.fit(X_train_scaled, y_train)

# Evaluate
y_pred = lr_model.predict(X_test_scaled)
y_prob = lr_model.predict_proba(X_test_scaled)[:, 1]

print(f"\n  Model Performance:")
print(f"  Accuracy: {(y_pred == y_test).mean():.4f}")
print(f"  ROC-AUC Score: {roc_auc_score(y_test, y_prob):.4f}")
print(f"\n  Classification Report:")
print(classification_report(y_test, y_pred, target_names=['Within SLA', 'SLA Breached']))

# Feature importance
feature_importance = pd.DataFrame({
    'Feature': feature_cols,
    'Coefficient': lr_model.coef_[0]
}).sort_values('Coefficient', key=abs, ascending=False)

fig_feature = px.bar(
    feature_importance,
    x='Coefficient',
    y='Feature',
    orientation='h',
    title='SLA Breach Prediction - Feature Importance',
    color='Coefficient',
    color_continuous_scale='RdBu_r'
)
fig_feature.update_layout(template='plotly_white')
fig_feature.write_html(IMG_DIR / 'sla_prediction_features.html')
fig_feature.write_image(IMG_DIR / 'sla_prediction_features.png', scale=2)
print("  Saved: sla_prediction_features")

# Save model artifacts
model_artifacts = {
    'model': lr_model,
    'scaler': scaler,
    'le_group': le_group,
    'le_channel': le_channel,
    'le_region': le_region,
    'feature_cols': feature_cols
}
import pickle
with open(OUTPUT_DIR / 'sla_breach_model.pkl', 'wb') as f:
    pickle.dump(model_artifacts, f)
print("  Saved: sla_breach_model.pkl")

# =============================================================================
# SECTION 3: WORKLOAD DISTRIBUTION HEATMAPS
# =============================================================================
print("\n[3] GENERATING WORKLOAD DISTRIBUTION HEATMAPS...")

# Prepare data for heatmap
df_incident['Month'] = df_incident['Opened_DT'].dt.to_period('M').astype(str)
df_incident['Hour'] = df_incident['Opened_DT'].dt.hour

# Volume by Region x Month
region_month = df_incident.pivot_table(
    index='Caller_Region', 
    columns='Month', 
    values='Incident_Number', 
    aggfunc='count',
    fill_value=0
)

fig_heat1 = px.imshow(
    region_month,
    labels=dict(x='Month', y='Region', color='Incident Count'),
    title='Incident Volume by Region and Month',
    color_continuous_scale='Viridis',
    aspect='auto'
)
fig_heat1.write_html(IMG_DIR / 'workload_region_month.html')
fig_heat1.write_image(IMG_DIR / 'workload_region_month.png', scale=2)
print("  Saved: workload_region_month")

# Volume by SBG x Month
sbg_month = df_incident.pivot_table(
    index='Caller_SBG', 
    columns='Month', 
    values='Incident_Number', 
    aggfunc='count',
    fill_value=0
)

fig_heat2 = px.imshow(
    sbg_month,
    labels=dict(x='Month', y='SBG', color='Incident Count'),
    title='Incident Volume by SBG and Month',
    color_continuous_scale='Plasma',
    aspect='auto'
)
fig_heat2.write_html(IMG_DIR / 'workload_sbg_month.html')
fig_heat2.write_image(IMG_DIR / 'workload_sbg_month.png', scale=2)
print("  Saved: workload_sbg_month")

# Volume by Hour x Day of Week
dow_hour = df_incident.pivot_table(
    index=df_incident['Opened_DT'].dt.dayofweek,
    columns='Hour',
    values='Incident_Number',
    aggfunc='count',
    fill_value=0
)
dow_hour.index = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

fig_heat3 = px.imshow(
    dow_hour,
    labels=dict(x='Hour of Day', y='Day of Week', color='Incident Count'),
    title='Incident Volume by Hour and Day of Week',
    color_continuous_scale='Blues',
    aspect='auto'
)
fig_heat3.write_html(IMG_DIR / 'workload_dow_hour.html')
fig_heat3.write_image(IMG_DIR / 'workload_dow_hour.png', scale=2)
print("  Saved: workload_dow_hour")

# =============================================================================
# SECTION 4: TEMPORAL TRENDING & DECOMPOSITION
# =============================================================================
print("\n[4] TEMPORAL TRENDING & DECOMPOSITION...")

# Daily incident counts
daily_incidents = df_incident.groupby(df_incident['Opened_DT'].dt.date).size().reset_index(name='Count')
daily_incidents.columns = ['Date', 'Count']
daily_incidents['Date'] = pd.to_datetime(daily_incidents['Date'])

# Calculate moving averages
daily_incidents['MA_7'] = daily_incidents['Count'].rolling(window=7, min_periods=1).mean()
daily_incidents['MA_30'] = daily_incidents['Count'].rolling(window=30, min_periods=1).mean()

fig_trend = go.Figure()
fig_trend.add_trace(go.Scatter(x=daily_incidents['Date'], y=daily_incidents['Count'], 
                               mode='markers', name='Daily Volume', marker=dict(size=4, color='lightgray')))
fig_trend.add_trace(go.Scatter(x=daily_incidents['Date'], y=daily_incidents['MA_7'], 
                               mode='lines', name='7-Day MA', line=dict(color='blue', width=2)))
fig_trend.add_trace(go.Scatter(x=daily_incidents['Date'], y=daily_incidents['MA_30'], 
                               mode='lines', name='30-Day MA', line=dict(color='red', width=2)))

fig_trend.update_layout(
    title='Daily Incident Volume with Moving Averages',
    xaxis_title='Date',
    yaxis_title='Incident Count',
    template='plotly_white',
    height=500
)
fig_trend.write_html(IMG_DIR / 'temporal_trend.html')
fig_trend.write_image(IMG_DIR / 'temporal_trend.png', scale=2)
print("  Saved: temporal_trend")

# Monthly resolved vs opened comparison
df_incident['Month_Opened'] = df_incident['Opened_DT'].dt.to_period('M')
df_incident['Month_Resolved'] = df_incident['Resolved_DT'].dt.to_period('M')

monthly_comp = pd.DataFrame({
    'Opened': df_incident.groupby('Month_Opened').size(),
    'Resolved': df_incident.dropna(subset=['Resolved_DT']).groupby('Month_Resolved').size()
}).fillna(0)
monthly_comp.index = monthly_comp.index.astype(str)

fig_comp = px.line(
    monthly_comp,
    markers=True,
    title='Monthly Opened vs Resolved Incidents',
    color_discrete_sequence=['#2E86AB', '#28A745']
)
fig_comp.update_layout(template='plotly_white', xaxis_title='Month', yaxis_title='Count')
fig_comp.write_html(IMG_DIR / 'temporal_opened_resolved.html')
fig_comp.write_image(IMG_DIR / 'temporal_opened_resolved.png', scale=2)
print("  Saved: temporal_opened_resolved")

# =============================================================================
# SECTION 5: CLOSURE CODE PARETO ANALYSIS
# =============================================================================
print("\n[5] CLOSURE CODE PARETO ANALYSIS...")

# Closure code frequency with impact weights
closure_weights = {
    'Configuration issue': 3,  # High impact - systemic
    'Data Issue': 2,           # Medium - requires attention
    'User / Human error / Training': 1,  # Lower - training needed
    'Service Request Created': 1,
    '3 Customer Contacts – No Response': 1,
    'Other': 2,
    'Duplicate Record': 1,
    'No Error Found': 1,
    'Software Error': 3,  # High - technical debt
    'Network Issue': 2,
    'Hardware Issue': 2,
    'Vendor Issue': 2,
    'Permit/Approve/Authorize': 1
}

closure_data = df_incident[df_incident['Closure_Code'].notna()]['Closure_Code'].value_counts().reset_index()
closure_data.columns = ['Closure_Code', 'Count']
closure_data['Impact_Weight'] = closure_data['Closure_Code'].map(closure_weights).fillna(2)
closure_data['Weighted_Score'] = closure_data['Count'] * closure_data['Impact_Weight']
closure_data['Cumulative_Pct'] = closure_data['Count'].cumsum() / closure_data['Count'].sum() * 100

# Pareto chart
fig_pareto = make_subplots(specs=[[{"secondary_y": True}]])

# Bar chart
fig_pareto.add_trace(
    go.Bar(
        x=closure_data['Closure_Code'],
        y=closure_data['Count'],
        name='Incident Count',
        marker_color='#2E86AB'
    ),
    secondary_y=False
)

# Cumulative line
fig_pareto.add_trace(
    go.Scatter(
        x=closure_data['Closure_Code'],
        y=closure_data['Cumulative_Pct'],
        name='Cumulative %',
        line=dict(color='#E74C3C', width=3, dash='dot')
    ),
    secondary_y=True
)

fig_pareto.add_hline(y=80, line_dash="dash", line_color="green", annotation_text="80% Threshold", secondary_y=True)
fig_pareto.update_layout(title='Closure Code Pareto Analysis', template='plotly_white')
fig_pareto.update_yaxes(title_text="Incident Count", secondary_y=False)
fig_pareto.update_yaxes(title_text="Cumulative %", secondary_y=True, range=[0, 105])
fig_pareto.write_html(IMG_DIR / 'pareto_closure_codes.html')
fig_pareto.write_image(IMG_DIR / 'pareto_closure_codes.png', scale=2)
print("  Saved: pareto_closure_codes")

# Closure code by SBG
closure_sbg = pd.crosstab(df_incident['Closure_Code'], df_incident['Caller_SBG'])
closure_sbg_top = closure_sbg.loc[closure_data['Closure_Code'].head(8)]

fig_closure_heatmap = px.imshow(
    closure_sbg_top,
    labels=dict(x='SBG', y='Closure Code', color='Count'),
    title='Closure Code Distribution by SBG',
    color_continuous_scale='YlOrRd',
    aspect='auto'
)
fig_closure_heatmap.write_html(IMG_DIR / 'closure_sbg_heatmap.html')
fig_closure_heatmap.write_image(IMG_DIR / 'closure_sbg_heatmap.png', scale=2)
print("  Saved: closure_sbg_heatmap")

# =============================================================================
# SECTION 6: TEXT MINING & INCIDENT CLUSTERING
# =============================================================================
print("\n[6] TEXT MINING & INCIDENT CLUSTERING...")

# Prepare text data
df_text = df_incident[df_incident['Short_Description'].notna() & (df_incident['Short_Description'].str.len() > 10)].copy()
df_text = df_text.head(10000)  # Limit for performance

# Clean text
def clean_text(text):
    text = str(text).lower()
    text = re.sub(r'[^a-zA-Z\s]', ' ', text)
    text = re.sub(r'\s+', ' ', text).strip()
    return text

df_text['Clean_Text'] = df_text['Short_Description'].apply(clean_text)

# TF-IDF Vectorization
print("  Vectorizing text with TF-IDF...")
tfidf = TfidfVectorizer(max_features=1000, stop_words='english', ngram_range=(1, 2), min_df=5)
tfidf_matrix = tfidf.fit_transform(df_text['Clean_Text'])

# K-Means Clustering
print("  Performing K-Means clustering...")
n_clusters = 8
kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
df_text['Cluster'] = kmeans.fit_predict(tfidf_matrix)

# Cluster size distribution
cluster_sizes = df_text['Cluster'].value_counts().sort_index()

# Cluster labels based on top terms
feature_names = tfidf.get_feature_names_out()
cluster_labels = []
for i in range(n_clusters):
    center = kmeans.cluster_centers_[i]
    top_terms_idx = center.argsort()[-3:][::-1]
    top_terms = [feature_names[j] for j in top_terms_idx]
    cluster_labels.append(f"Cluster {i}: {', '.join(top_terms)}")

# Visualize clusters
fig_clusters = px.bar(
    x=[f"Cluster {i}" for i in range(n_clusters)],
    y=cluster_sizes.values,
    color=cluster_sizes.values,
    color_continuous_scale='Viridis',
    title='Incident Clusters Based on Short Description',
    labels={'x': 'Cluster', 'y': 'Number of Incidents'}
)
fig_clusters.update_layout(template='plotly_white')
fig_clusters.write_html(IMG_DIR / 'text_cluster_sizes.html')
fig_clusters.write_image(IMG_DIR / 'text_cluster_sizes.png', scale=2)
print("  Saved: text_cluster_sizes")

# Cluster details
cluster_details = df_text.groupby('Cluster').agg({
    'Priority_Num': 'mean',
    'MTTR_Hours': 'mean' if 'MTTR_Hours' in df_text.columns else 'count',
    'Incident_Number': 'count'
}).round(2)
cluster_details['Top_Terms'] = cluster_labels
print("\n  Cluster Summary:")
for idx, row in cluster_details.iterrows():
    print(f"    {row['Top_Terms'][:50]}: {row['Incident_Number']} incidents, Avg Priority: {row['Priority_Num']:.2f}")

# =============================================================================
# SECTION 7: REOPEN COUNT ANOMALY DETECTION
# =============================================================================
print("\n[7] REOPEN COUNT ANOMALY DETECTION...")

# Z-score based anomaly detection
reopens = df_incident['Reopen_Count']
mean_reopens = reopens.mean()
std_reopens = reopens.std()
z_threshold = 3

df_incident['Reopen_ZScore'] = (reopens - mean_reopens) / std_reopens
df_incident['Is_Anomaly'] = df_incident['Reopen_ZScore'].abs() > z_threshold

# Anomaly summary
anomalies = df_incident[df_incident['Is_Anomaly']]
print(f"  Anomalous incidents (Z-score > 3): {len(anomalies):,}")

# Reopen distribution with outliers highlighted
fig_reopens = px.histogram(
    df_incident, 
    x='Reopen_Count',
    nbins=50,
    color='Is_Anomaly',
    color_discrete_map={True: 'red', False: 'blue'},
    title='Reopen Count Distribution with Anomalies Highlighted',
    labels={'Reopen_Count': 'Reopen Count', 'Is_Anomaly': 'Is Anomaly?'}
)
fig_reopens.update_layout(template='plotly_white', barmode='overlay')
fig_reopens.update_traces(opacity=0.7)
fig_reopens.write_html(IMG_DIR / 'reopen_anomalies.html')
fig_reopens.write_image(IMG_DIR / 'reopen_anomalies.png', scale=2)
print("  Saved: reopen_anomalies")

# High reopen incidents by Assignment Group
reopen_by_group = df_incident.groupby('Assignment_Group').agg({
    'Reopen_Count': ['sum', 'mean', 'max'],
    'Is_Anomaly': 'sum'
}).round(3)
reopen_by_group.columns = ['Total_Reopens', 'Avg_Reopens', 'Max_Reopens', 'Anomaly_Count']
reopen_by_group = reopen_by_group.sort_values('Anomaly_Count', ascending=False).head(15)

fig_reopen_group = px.bar(
    reopen_by_group.reset_index(),
    x='Anomaly_Count',
    y='Assignment_Group',
    orientation='h',
    color='Avg_Reopens',
    color_continuous_scale='Reds',
    title='High Reopen Anomalies by Assignment Group',
    labels={'Anomaly_Count': 'Anomaly Count', 'Assignment_Group': 'Assignment Group'}
)
fig_reopen_group.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig_reopen_group.write_html(IMG_DIR / 'reopen_by_group.html')
fig_reopen_group.write_image(IMG_DIR / 'reopen_by_group.png', scale=2)
print("  Saved: reopen_by_group")

# =============================================================================
# SECTION 8: PARENT-CHILD INCIDENT ANALYSIS
# =============================================================================
print("\n[8] PARENT-CHILD INCIDENT RELATIONSHIP ANALYSIS...")

parent_incidents = df_incident[df_incident['Parent_Incident'].notna()].copy()
child_incidents = df_incident[df_incident['Parent_Incident'].isin(df_incident['Incident_Number'])].copy()

print(f"  Parent incidents: {parent_incidents['Parent_Incident'].nunique():,}")
print(f"  Child incidents linked to parents: {len(child_incidents):,}")

# Parent-child relationship analysis
if len(parent_incidents) > 0:
    parent_summary = parent_incidents.groupby('Parent_Incident').agg({
        'Incident_Number': 'count',
        'MTTR_Hours': 'mean',
        'Priority_Num': 'first',
        'Assignment_Group': 'first'
    }).reset_index()
    parent_summary.columns = ['Parent_Incident', 'Child_Count', 'Parent_MTTR', 'Parent_Priority', 'Assignment_Group']
    parent_summary = parent_summary.sort_values('Child_Count', ascending=False)

    fig_parent = px.histogram(
        parent_summary,
        x='Child_Count',
        nbins=20,
        title='Distribution of Child Incidents per Parent Incident',
        color_discrete_sequence=['#28A745']
    )
    fig_parent.update_layout(template='plotly_white')
    fig_parent.write_html(IMG_DIR / 'parent_child_distribution.html')
    fig_parent.write_image(IMG_DIR / 'parent_child_distribution.png', scale=2)
    print("  Saved: parent_child_distribution")

# Top parent incidents by child count
top_parents = parent_summary.head(10)[['Parent_Incident', 'Child_Count', 'Assignment_Group']]
fig_top_parents = px.bar(
    top_parents,
    x='Child_Count',
    y='Parent_Incident',
    orientation='h',
    color='Child_Count',
    color_continuous_scale='Oranges',
    title='Top 10 Parent Incidents by Child Count'
)
fig_top_parents.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig_top_parents.write_html(IMG_DIR / 'top_parent_incidents.html')
fig_top_parents.write_image(IMG_DIR / 'top_parent_incidents.png', scale=2)
print("  Saved: top_parent_incidents")

# =============================================================================
# SECTION 9: BACKLOG AGING ANALYSIS
# =============================================================================
print("\n[9] BACKLOG AGING ANALYSIS...")

# Identify open/pending incidents
open_states = ['Open', 'Work in progress', 'Pending', 'Pending Customer', 'Pending Vendor']
df_incident['Is_Open'] = df_incident['State'].isin(['Closed', 'Cancelled', 'Resolved']) == False

open_incidents = df_incident[df_incident['Is_Open']].copy()
open_incidents['Days_Open'] = (pd.Timestamp.now() - open_incidents['Opened_DT']).dt.total_seconds() / 86400

# Backlog age by Assignment Group
backlog_by_group = open_incidents.groupby('Assignment_Group').agg({
    'Days_Open': ['mean', 'max', 'count']
}).round(1)
backlog_by_group.columns = ['Avg_Age_Days', 'Max_Age_Days', 'Open_Count']
backlog_by_group = backlog_by_group.sort_values('Avg_Age_Days', ascending=False)

# Backlog aging buckets
def age_bucket(days):
    if pd.isna(days):
        return 'Unknown'
    elif days <= 1:
        return '1 Day'
    elif days <= 7:
        return '1-7 Days'
    elif days <= 30:
        return '7-30 Days'
    elif days <= 90:
        return '30-90 Days'
    else:
        return '90+ Days'

open_incidents['Age_Bucket'] = open_incidents['Days_Open'].apply(age_bucket)
age_distribution = open_incidents['Age_Bucket'].value_counts().reset_index()
age_distribution.columns = ['Age_Bucket', 'Count']

fig_backlog = px.bar(
    age_distribution,
    x='Age_Bucket',
    y='Count',
    color='Count',
    color_continuous_scale='Reds',
    title='Open Incident Backlog by Age',
)
fig_backlog.update_layout(template='plotly_white')
fig_backlog.write_html(IMG_DIR / 'backlog_age_distribution.html')
fig_backlog.write_image(IMG_DIR / 'backlog_age_distribution.png', scale=2)
print("  Saved: backlog_age_distribution")

# Backlog by Assignment Group (Top 15 oldest)
fig_backlog_group = px.bar(
    backlog_by_group.reset_index().head(15),
    x='Avg_Age_Days',
    y='Assignment_Group',
    orientation='h',
    color='Avg_Age_Days',
    color_continuous_scale='RdYlGn_r',
    title='Average Backlog Age by Assignment Group (Top 15)',
    labels={'Avg_Age_Days': 'Average Age (Days)', 'Assignment_Group': 'Assignment Group'}
)
fig_backlog_group.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig_backlog_group.write_html(IMG_DIR / 'backlog_by_group.html')
fig_backlog_group.write_image(IMG_DIR / 'backlog_by_group.png', scale=2)
print("  Saved: backlog_by_group")

# =============================================================================
# SECTION 10: AGENT RESOLUTION VELOCITY PROFILING
# =============================================================================
print("\n[10] AGENT RESOLUTION VELOCITY PROFILING...")

# Filter to incidents with assigned agents
agent_incidents = df_incident[df_incident['Assigned_To'].notna()].copy()
agent_incidents = agent_incidents[agent_incidents['Resolved_DT'].notna()]
agent_incidents['MTTR_Hours'] = (agent_incidents['Resolved_DT'] - agent_incidents['Opened_DT']).dt.total_seconds() / 3600

# Agent performance profile
agent_profile = agent_incidents.groupby('Assigned_To').agg({
    'MTTR_Hours': ['mean', 'median', 'count'],
    'Reopen_Count': 'sum',
    'SLA_Breached': 'mean'
}).round(2)
agent_profile.columns = ['Avg_MTTR', 'Median_MTTR', 'Total_Resolved', 'Total_Reopens', 'SLA_Breach_Rate']
agent_profile = agent_profile[agent_profile['Total_Resolved'] >= 10]  # Filter for minimum volume
agent_profile = agent_profile.sort_values('Avg_MTTR')

# Top performers (lowest MTTR)
top_performers = agent_profile.head(10).reset_index()

fig_agent = px.scatter(
    top_performers,
    x='Total_Resolved',
    y='Avg_MTTR',
    size='SLA_Breach_Rate',
    hover_name='Assigned_To',
    color='Median_MTTR',
    color_continuous_scale='Viridis',
    title='Top 10 Performing Agents by Resolution Velocity',
    labels={'Total_Resolved': 'Incidents Resolved', 'Avg_MTTR': 'Average MTTR (Hours)'}
)
fig_agent.update_layout(template='plotly_white')
fig_agent.write_html(IMG_DIR / 'agent_performance_top.html')
fig_agent.write_image(IMG_DIR / 'agent_performance_top.png', scale=2)
print("  Saved: agent_performance_top")

# Low performers (highest MTTR)
low_performers = agent_profile.tail(10).sort_values('Avg_MTTR', ascending=False).reset_index()

fig_agent_low = px.scatter(
    low_performers,
    x='Total_Resolved',
    y='Avg_MTTR',
    size='Total_Reopens',
    hover_name='Assigned_To',
    color='SLA_Breach_Rate',
    color_continuous_scale='Reds',
    title='Agents Requiring Performance Review (Highest MTTR)',
    labels={'Total_Resolved': 'Incidents Resolved', 'Avg_MTTR': 'Average MTTR (Hours)'}
)
fig_agent_low.update_layout(template='plotly_white')
fig_agent_low.write_html(IMG_DIR / 'agent_performance_low.html')
fig_agent_low.write_image(IMG_DIR / 'agent_performance_low.png', scale=2)
print("  Saved: agent_performance_low")

# =============================================================================
# SECTION 11: SKILLS MATRIX (CI EXPERTISE)
# =============================================================================
print("\n[11] SKILLS MATRIX DEVELOPMENT...")

# CI expertise by Assignment Group
ci_expertise = pd.crosstab(df_incident['Assignment_Group'], df_incident['Configuration_Item'])

# Top CIs per Assignment Group
skills_matrix = df_incident.groupby(['Assignment_Group', 'Configuration_Item']).size().reset_index(name='Count')
skills_matrix = skills_matrix.sort_values(['Assignment_Group', 'Count'], ascending=[True, False])
top_skills = skills_matrix.groupby('Assignment_Group').head(5)

# Pivot for heatmap (top 10 assignment groups by volume)
top_groups = df_incident['Assignment_Group'].value_counts().head(10).index
skills_pivot = top_skills[top_skills['Assignment_Group'].isin(top_groups)].pivot_table(
    index='Assignment_Group',
    columns='Configuration_Item',
    values='Count',
    fill_value=0
)

fig_skills = px.imshow(
    skills_pivot,
    labels=dict(x='Configuration Item', y='Assignment Group', color='Incident Count'),
    title='Skills Matrix: Assignment Group vs Configuration Item',
    color_continuous_scale='Blues',
    aspect='auto'
)
fig_skills.write_html(IMG_DIR / 'skills_matrix.html')
fig_skills.write_image(IMG_DIR / 'skills_matrix.png', scale=2)
print("  Saved: skills_matrix")

# =============================================================================
# SECTION 12: CI FAILURE RATE RANKING
# =============================================================================
print("\n[12] CONFIGURATION ITEM FAILURE RATE RANKING...")

ci_stats = df_incident.groupby('Configuration_Item').agg({
    'Incident_Number': 'count',
    'Priority_Num': 'mean',
    'SLA_Breached': 'mean',
    'MTTR_Hours': 'mean'
}).round(2)
ci_stats.columns = ['Incident_Count', 'Avg_Priority', 'SLA_Breach_Rate', 'Avg_MTTR_Hours']
ci_stats = ci_stats.sort_values('Incident_Count', ascending=False)

# Filter for significant CIs (min 50 incidents)
significant_ci = ci_stats[ci_stats['Incident_Count'] >= 50].head(20)

fig_ci = px.bar(
    significant_ci.reset_index(),
    x='Incident_Count',
    y='Configuration_Item',
    orientation='h',
    color='SLA_Breach_Rate',
    color_continuous_scale='RdYlGn_r',
    title='Top 20 Configuration Items by Incident Volume (Colored by SLA Breach Rate)',
    labels={'Incident_Count': 'Incident Count', 'Configuration_Item': 'Configuration Item'}
)
fig_ci.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig_ci.write_html(IMG_DIR / 'ci_failure_ranking.html')
fig_ci.write_image(IMG_DIR / 'ci_failure_ranking.png', scale=2)
print("  Saved: ci_failure_ranking")

# =============================================================================
# SECTION 13: EDI/B2Bi INTEGRATION ANALYSIS
# =============================================================================
print("\n[13] EDI & B2Bi INTEGRATION ERROR ANALYSIS...")

# Filter for integration-related incidents
edi_keywords = ['edi', 'b2b', 'b2bi', 'integration', 'exchange', 'gateway']
df_incident['Integration_Lower'] = df_incident['Integration_Name'].fillna('').str.lower()

edi_incidents = df_incident[
    df_incident['Integration_Lower'].str.contains('|'.join(edi_keywords), na=False) |
    df_incident['Assignment_Group'].str.contains('EDI|Integration', case=False, na=False)
].copy()

print(f"  EDI/B2Bi related incidents: {len(edi_incidents):,}")

if len(edi_incidents) > 0:
    edi_by_integration = edi_incidents['Integration_Name'].value_counts().head(15)
    
    fig_edi = px.bar(
        x=edi_by_integration.index,
        y=edi_by_integration.values,
        color=edi_by_integration.values,
        color_continuous_scale='Oranges',
        title='EDI/B2Bi Integration Incident Volume',
        labels={'x': 'Integration Name', 'y': 'Incident Count'}
    )
    fig_edi.update_layout(template='plotly_white', xaxis_title='Integration Name')
    fig_edi.write_html(IMG_DIR / 'edi_integration_analysis.html')
    fig_edi.write_image(IMG_DIR / 'edi_integration_analysis.png', scale=2)
    print("  Saved: edi_integration_analysis")
    
    # EDI incidents by Category
    edi_category = edi_incidents['Category'].value_counts().head(10)
    fig_edi_cat = px.bar(
        x=edi_category.index,
        y=edi_category.values,
        color=edi_category.values,
        color_continuous_scale='Purples',
        title='EDI/B2Bi Incidents by Category'
    )
    fig_edi_cat.update_layout(template='plotly_white')
    fig_edi_cat.write_html(IMG_DIR / 'edi_category.html')
    fig_edi_cat.write_image(IMG_DIR / 'edi_category.png', scale=2)
    print("  Saved: edi_category")

# =============================================================================
# SECTION 14: VENDOR IMPACT ASSESSMENT
# =============================================================================
print("\n[14] VENDOR IMPACT ASSESSMENT...")

vendor_incidents = df_incident[df_incident['Vendor'].notna()].copy()
print(f"  Incidents with vendor assignment: {len(vendor_incidents):,}")

if len(vendor_incidents) > 0:
    vendor_stats = vendor_incidents.groupby('Vendor').agg({
        'Incident_Number': 'count',
        'SLA_Breached': 'mean',
        'MTTR_Hours': 'mean',
        'Reopen_Count': 'sum'
    }).round(2)
    vendor_stats.columns = ['Incident_Count', 'SLA_Breach_Rate', 'Avg_MTTR', 'Total_Reopens']
    vendor_stats = vendor_stats.sort_values('Incident_Count', ascending=False)
    
    # Top vendors by volume
    top_vendors = vendor_stats.head(15)
    
    fig_vendor = px.bar(
        top_vendors.reset_index(),
        x='Incident_Count',
        y='Vendor',
        orientation='h',
        color='SLA_Breach_Rate',
        color_continuous_scale='RdYlGn_r',
        title='Vendor Impact Assessment (Top 15 by Volume)',
        labels={'Incident_Count': 'Incident Count', 'Vendor': 'Vendor'}
    )
    fig_vendor.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
    fig_vendor.write_html(IMG_DIR / 'vendor_impact.html')
    fig_vendor.write_image(IMG_DIR / 'vendor_impact.png', scale=2)
    print("  Saved: vendor_impact")

# =============================================================================
# SECTION 15: AI AGENTS & AUTOMATION IMPACT ANALYSIS
# =============================================================================
print("\n[15] AI AGENTS & AUTOMATION IMPACT ANALYSIS...")

# Channel distribution for automation analysis
channel_stats = df_incident.groupby('Channel').agg({
    'Incident_Number': 'count',
    'SLA_Breached': 'mean',
    'MTTR_Hours': 'mean',
    'Reopen_Count': 'mean'
}).round(2)
channel_stats.columns = ['Volume', 'SLA_Breach_Rate', 'Avg_MTTR', 'Avg_Reopens']

# Self-service and Virtual Agent analysis
automation_channels = ['Self-service', 'Virtual Agent']
other_channels = [c for c in channel_stats.index if c not in automation_channels]

automation_stats = channel_stats.loc[automation_channels] if all(c in channel_stats.index for c in automation_channels) else pd.DataFrame()
non_automation_stats = channel_stats.loc[other_channels] if other_channels else pd.DataFrame()

# Compare automation vs traditional channels
if len(automation_stats) > 0 and len(non_automation_stats) > 0:
    # Create comparison for Volume, SLA Breach Rate, and Avg MTTR
    metrics = ['Volume', 'SLA_Breach_Rate', 'Avg_MTTR']
    automation_vals = [automation_stats.loc[c, m] if c in automation_stats.index else 0 
                       for c in automation_stats.index for m in metrics]
    traditional_vals = [non_automation_stats.loc[c, m] if c in non_automation_stats.index else 0 
                        for c in non_automation_stats.index for m in metrics]
    
    comparison_data = pd.DataFrame({
        'Channel_Type': ['Automation'] * 3 + ['Traditional'] * 3,
        'Metric': metrics * 2,
        'Value': automation_vals[:3] + traditional_vals[:3]
    })
    
    fig_automation = px.bar(
        comparison_data,
        x='Channel_Type',
        y='Value',
        color='Metric',
        barmode='group',
        title='Automation Channels vs Traditional Channels Performance',
        color_discrete_sequence=['#2E86AB', '#28A745', '#E74C3C']
    )
    fig_automation.update_layout(template='plotly_white')
    fig_automation.write_html(IMG_DIR / 'automation_impact.html')
    fig_automation.write_image(IMG_DIR / 'automation_impact.png', scale=2)
    print("  Saved: automation_impact")

# Channel trend over time
df_incident['Month'] = df_incident['Opened_DT'].dt.to_period('M').astype(str)
channel_trend = df_incident.pivot_table(
    index='Month',
    columns='Channel',
    values='Incident_Number',
    aggfunc='count',
    fill_value=0
)

fig_channel_trend = px.line(
    channel_trend,
    markers=True,
    title='Channel Volume Trend Over Time',
    color_discrete_sequence=px.colors.qualitative.Bold
)
fig_channel_trend.update_layout(template='plotly_white', xaxis_title='Month', yaxis_title='Incident Count')
fig_channel_trend.write_html(IMG_DIR / 'channel_trend.html')
fig_channel_trend.write_image(IMG_DIR / 'channel_trend.png', scale=2)
print("  Saved: channel_trend")

# Self-service and Virtual Agent efficiency
fig_channel_box = px.box(
    df_incident[df_incident['Channel'].isin(['Self-service', 'Virtual Agent', 'Integration'])],
    x='Channel',
    y='MTTR_Hours',
    color='Channel',
    log_y=True,
    title='MTTR Distribution by Channel'
)
fig_channel_box.update_layout(template='plotly_white', showlegend=False)
fig_channel_box.write_html(IMG_DIR / 'channel_mttr_box.html')
fig_channel_box.write_image(IMG_DIR / 'channel_mttr_box.png', scale=2)
print("  Saved: channel_mttr_box")

# =============================================================================
# SAVE COMPREHENSIVE ANALYTICS RESULTS
# =============================================================================
print("\n[16] SAVING ANALYTICS RESULTS...")

# Save all key statistics
analytics_results = {
    'mttr_by_priority': mttr_by_priority,
    'sla_compliance': sla_compliance,
    'sla_by_group': sla_by_group,
    'feature_importance': feature_importance,
    'closure_analysis': closure_data,
    'agent_profile': agent_profile,
    'ci_stats': ci_stats,
    'channel_stats': channel_stats
}

for name, df_res in analytics_results.items():
    if hasattr(df_res, 'to_csv'):
        df_res.to_csv(OUTPUT_DIR / f'{name}.csv')

print("  Saved all analytics results to temp_files/")

print("\n" + "=" * 80)
print("PHASE 3 COMPLETE - Deep Analysis Finished")
print("=" * 80)
print(f"\nGenerated visualizations:")
print(f"  - SLA Performance: sla_mttr_by_priority, sla_breach_by_group")
print(f"  - Prediction Model: sla_prediction_features")
print(f"  - Workload: workload_region_month, workload_sbg_month, workload_dow_hour")
print(f"  - Temporal: temporal_trend, temporal_opened_resolved")
print(f"  - Closure Codes: pareto_closure_codes, closure_sbg_heatmap")
print(f"  - Text Mining: text_cluster_sizes")
print(f"  - Anomalies: reopen_anomalies, reopen_by_group")
print(f"  - Parent-Child: parent_child_distribution, top_parent_incidents")
print(f"  - Backlog: backlog_age_distribution, backlog_by_group")
print(f"  - Agent Performance: agent_performance_top, agent_performance_low")
print(f"  - Skills Matrix: skills_matrix")
print(f"  - CI Ranking: ci_failure_ranking")
print(f"  - EDI/B2Bi: edi_integration_analysis, edi_category")
print(f"  - Vendor: vendor_impact")
print(f"  - Automation: automation_impact, channel_trend, channel_mttr_box")
