"""
Phase 2: Cleaning & Exploratory Data Analysis (EDA)
Data cleaning, foundational visualizations, correlation analysis.
"""

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
import warnings
warnings.filterwarnings('ignore')

# Paths
DATA_DIR = Path('/app/workspace/user_source_data')
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 raw data
print("=" * 80)
print("PHASE 2: DATA CLEANING & EDA")
print("=" * 80)

df_service = pd.read_pickle(OUTPUT_DIR / 'service_tasks_raw.pkl')
df_incident = pd.read_pickle(OUTPUT_DIR / 'incident_dump_raw.pkl')

# =============================================================================
# CLEANING: SERVICE TASKS
# =============================================================================
print("\n[1] CLEANING SERVICE TASKS...")

# Columns to drop (100% nulls)
drop_cols_service = ['Change ID', 'Request Category', 'Request Subcategory', 
                      'Project ID', 'Required Approval', 'IT Service']
df_service = df_service.drop(columns=[c for c in drop_cols_service if c in df_service.columns])

# Rename columns for consistency
rename_map_service = {
    'Name': 'Requester_Name',
    'User ID': 'Requester_ID',
    'Region': 'Requester_Region',
    'SBU': 'Requester_SBU',
    'SBG': 'Requester_SBG',
    'GBE': 'Requester_GBE',
    'User ID.1': 'Assignee_ID',
    'Region.1': 'Assignee_Region',
    'SBU.1': 'Assignee_SBU',
    'SBG.1': 'Assignee_SBG',
    'GBE.1': 'Assignee_GBE',
    'Opened by': 'Opened_By',
    'User ID.2': 'Opened_By_ID',
    'Number': 'Task_Number',
    'Request item': 'RITM_Number',
    'Number.1': 'RITM_Number_Alt',
    'Parent': 'Parent_Task',
}
df_service = df_service.rename(columns=rename_map_service)

# Parse dates
df_service['Opened_DT'] = pd.to_datetime(df_service['Opened'], errors='coerce')
# Create resolved date from Opened + a time delta (approximate for incomplete records)
# For now, keep as datetime

# Clean priority mapping
priority_map = {'1 - Critical': 1, '2 - High': 2, '3 - Moderate': 3, '4 - Low': 4}
df_service['Priority_Num'] = df_service['Priority'].map(priority_map).fillna(4)

# Calculate MTTR in hours (for records with Resolved time if available)
if 'Resolved' in df_service.columns:
    df_service['Resolved_DT'] = pd.to_datetime(df_service['Resolved'], errors='coerce')
    df_service['MTTR_Hours'] = (df_service['Resolved_DT'] - df_service['Opened_DT']).dt.total_seconds() / 3600

print(f"  Service Tasks cleaned: {df_service.shape}")

# =============================================================================
# CLEANING: INCIDENT DUMP
# =============================================================================
print("\n[2] CLEANING INCIDENT DUMP...")

# Columns to drop (100% nulls or not useful)
drop_cols_incident = ['Critical Priority MTTR', 'High Priority MTTR', 'Project ID']
df_incident = df_incident.drop(columns=[c for c in drop_cols_incident if c in df_incident.columns])

# Rename columns
rename_map_incident = {
    'Caller': 'Caller_Name',
    'User ID': 'Caller_ID',
    'Region': 'Caller_Region',
    'SBG1': 'Caller_SBG',
    'SBU': 'Caller_SBU',
    'Name': 'Caller_Name_Alt',
    'GBE': 'Caller_GBE',
    'Number': 'Incident_Number',
    'Parent Incident': 'Parent_Incident',
    'Opened': 'Opened_DT',
    'Resolved': 'Resolved_DT',
    'Impacted SBGs': 'Impacted_SBGs',
    'Configuration item': 'Configuration_Item',
    'Assignment group': 'Assignment_Group',
    'Assigned to': 'Assigned_To',
    'State': 'State',
    'Priority': 'Priority',
    'Description': 'Description',
    'Short description': 'Short_Description',
    'Caused by External Change ID': 'External_Change_ID',
    'Vendor': 'Vendor',
    'Vendor Ticket Number/Project Code': 'Vendor_Ticket',
    'Closure Code': 'Closure_Code',
    'Resolution notes': 'Resolution_Notes',
    'Resolving Business Service Name': 'Business_Service',
    'Integration Name': 'Integration_Name',
    'Category': 'Category',
    'Subcategory': 'Subcategory',
    'Made SLA': 'Made_SLA',
    'Service Restored / Workaround': 'Workaround',
    'Escalation': 'Escalation',
    'Reopen count': 'Reopen_Count',
    'Channel': 'Channel',
}
df_incident = df_incident.rename(columns=rename_map_incident)

# Parse dates
df_incident['Opened_DT'] = pd.to_datetime(df_incident['Opened_DT'], errors='coerce')
df_incident['Resolved_DT'] = pd.to_datetime(df_incident['Resolved_DT'], errors='coerce')

# Calculate MTTR in hours
df_incident['MTTR_Hours'] = (df_incident['Resolved_DT'] - df_incident['Opened_DT']).dt.total_seconds() / 3600

# Clean priority mapping
df_incident['Priority_Num'] = df_incident['Priority'].map(priority_map).fillna(3)

# Create SLA breach flag
# SLA targets: Critical=1hr, High=4hrs, Moderate=16hrs, Low=48hrs
sla_targets = {1: 1, 2: 4, 3: 16, 4: 48}
df_incident['SLA_Target_Hours'] = df_incident['Priority_Num'].map(sla_targets)
df_incident['SLA_Breached'] = df_incident.apply(
    lambda x: 1 if pd.notna(x['Resolved_DT']) and x['MTTR_Hours'] > x['SLA_Target_Hours'] else 0, 
    axis=1
)

print(f"  Incident Dump cleaned: {df_incident.shape}")

# =============================================================================
# EDA VISUALIZATIONS
# =============================================================================
print("\n[3] GENERATING EDA VISUALIZATIONS...")

# --- Figure 1: Incident Volume by State ---
fig1 = px.histogram(
    df_incident, 
    x='State', 
    color='Priority',
    title='Incident Volume by State and Priority',
    text_auto=True,
    color_discrete_sequence=px.colors.qualitative.Bold
)
fig1.update_layout(bargap=0.2, template='plotly_white')
fig1.write_html(IMG_DIR / 'eda_incident_state_priority.html')
fig1.write_image(IMG_DIR / 'eda_incident_state_priority.png', scale=2)
print("  Saved: eda_incident_state_priority")

# --- Figure 2: Service Tasks State Distribution ---
fig2 = px.histogram(
    df_service, 
    x='State', 
    color='Priority',
    title='Service Tasks State Distribution',
    text_auto=True,
    color_discrete_sequence=px.colors.qualitative.Set2
)
fig2.update_layout(bargap=0.2, template='plotly_white')
fig2.write_html(IMG_DIR / 'eda_service_tasks_state.html')
fig2.write_image(IMG_DIR / 'eda_service_tasks_state.png', scale=2)
print("  Saved: eda_service_tasks_state")

# --- Figure 3: Regional Distribution (Incidents by Region and SBG) ---
fig3 = px.treemap(
    df_incident.dropna(subset=['Caller_Region', 'Caller_SBG']),
    path=['Caller_Region', 'Caller_SBG'],
    title='Incident Distribution by Region and SBG',
    color='Caller_Region',
    color_discrete_sequence=px.colors.qualitative.Pastel
)
fig3.write_html(IMG_DIR / 'eda_region_sbg_treemap.html')
fig3.write_image(IMG_DIR / 'eda_region_sbg_treemap.png', scale=2)
print("  Saved: eda_region_sbg_treemap")

# --- Figure 4: Assignment Group Volume (Top 15) ---
top_groups = df_incident['Assignment_Group'].value_counts().head(15).reset_index()
top_groups.columns = ['Assignment_Group', 'Count']
fig4 = px.bar(
    top_groups, 
    x='Count', 
    y='Assignment_Group',
    orientation='h',
    title='Top 15 Assignment Groups by Incident Volume',
    color='Count',
    color_continuous_scale='Viridis'
)
fig4.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig4.write_html(IMG_DIR / 'eda_assignment_groups.html')
fig4.write_image(IMG_DIR / 'eda_assignment_groups.png', scale=2)
print("  Saved: eda_assignment_groups")

# --- Figure 5: Channel Distribution (Incidents) ---
fig5 = px.pie(
    df_incident, 
    names='Channel', 
    title='Incident Volume by Channel',
    hole=0.4,
    color_discrete_sequence=px.colors.qualitative.Pastel
)
fig5.write_html(IMG_DIR / 'eda_channel_distribution.html')
fig5.write_image(IMG_DIR / 'eda_channel_distribution.png', scale=2)
print("  Saved: eda_channel_distribution")

# --- Figure 6: Priority Distribution Comparison ---
fig6 = make_subplots(rows=1, cols=2, subplot_titles=('Incidents by Priority', 'Service Tasks by Priority'))

# Incidents
priority_counts_inc = df_incident['Priority'].value_counts().reset_index()
priority_counts_inc.columns = ['Priority', 'Count']
fig6.add_trace(go.Bar(x=priority_counts_inc['Priority'], y=priority_counts_inc['Count'], 
                      name='Incidents', marker_color='#2E86AB'), row=1, col=1)

# Service Tasks
priority_counts_svc = df_service['Priority'].value_counts().reset_index()
priority_counts_svc.columns = ['Priority', 'Count']
fig6.add_trace(go.Bar(x=priority_counts_svc['Priority'], y=priority_counts_svc['Count'], 
                      name='Service Tasks', marker_color='#A23B72'), row=1, col=2)

fig6.update_layout(template='plotly_white', showlegend=False, height=400)
fig6.write_html(IMG_DIR / 'eda_priority_comparison.html')
fig6.write_image(IMG_DIR / 'eda_priority_comparison.png', scale=2)
print("  Saved: eda_priority_comparison")

# --- Figure 7: Closure Code Distribution (Pareto-ready) ---
closure_counts = df_incident['Closure_Code'].value_counts().head(10).reset_index()
closure_counts.columns = ['Closure_Code', 'Count']
fig7 = px.bar(
    closure_counts, 
    x='Count', 
    y='Closure_Code',
    orientation='h',
    title='Top 10 Closure Codes',
    color='Count',
    color_continuous_scale='Reds'
)
fig7.update_layout(yaxis={'categoryorder':'total ascending'}, template='plotly_white')
fig7.write_html(IMG_DIR / 'eda_closure_codes.html')
fig7.write_image(IMG_DIR / 'eda_closure_codes.png', scale=2)
print("  Saved: eda_closure_codes")

# --- Figure 8: Monthly Trend of Incidents ---
df_incident['Month'] = df_incident['Opened_DT'].dt.to_period('M')
monthly_incidents = df_incident.groupby('Month').size().reset_index(name='Count')
monthly_incidents['Month_Str'] = monthly_incidents['Month'].astype(str)

fig8 = px.line(
    monthly_incidents, 
    x='Month_Str', 
    y='Count',
    markers=True,
    title='Monthly Incident Volume Trend (2025)',
    line_shape='spline'
)
fig8.update_traces(line_color='#2E86AB', marker_size=8)
fig8.update_layout(template='plotly_white', xaxis_title='Month', yaxis_title='Incident Count')
fig8.write_html(IMG_DIR / 'eda_monthly_trend.html')
fig8.write_image(IMG_DIR / 'eda_monthly_trend.png', scale=2)
print("  Saved: eda_monthly_trend")

# --- Figure 9: Reopen Count Distribution ---
fig9 = px.histogram(
    df_incident, 
    x='Reopen_Count',
    nbins=50,
    title='Incident Reopen Count Distribution',
    color_discrete_sequence=['#E74C3C']
)
fig9.update_layout(template='plotly_white')
fig9.write_html(IMG_DIR / 'eda_reopen_distribution.html')
fig9.write_image(IMG_DIR / 'eda_reopen_distribution.png', scale=2)
print("  Saved: eda_reopen_distribution")

# --- Figure 10: MTTR by Priority (Incidents) ---
# Filter to resolved incidents only
resolved_incidents = df_incident[df_incident['Resolved_DT'].notna() & (df_incident['MTTR_Hours'] > 0)]

fig10 = px.box(
    resolved_incidents, 
    x='Priority', 
    y='MTTR_Hours',
    title='MTTR Distribution by Priority (Incidents)',
    color='Priority',
    log_y=True
)
fig10.update_layout(template='plotly_white', showlegend=False)
fig10.write_html(IMG_DIR / 'eda_mttr_by_priority.html')
fig10.write_image(IMG_DIR / 'eda_mttr_by_priority.png', scale=2)
print("  Saved: eda_mttr_by_priority")

# =============================================================================
# SUMMARY STATISTICS
# =============================================================================
print("\n[4] GENERATING SUMMARY STATISTICS...")

summary_stats = {
    'Metric': [
        'Total Incidents',
        'Total Service Tasks',
        'Incident Resolution Rate',
        'Average MTTR (Hours) - Incidents',
        'Median MTTR (Hours) - Incidents',
        'SLA Breach Rate (Incidents)',
        'Incidents with Reopens > 0',
        'Top Closure Code',
        'Top Assignment Group',
        'Top Region (Incidents)'
    ],
    'Value': [
        f"{len(df_incident):,}",
        f"{len(df_service):,}",
        f"{len(df_incident[df_incident['State'] == 'Closed']) / len(df_incident) * 100:.1f}%",
        f"{resolved_incidents['MTTR_Hours'].mean():.2f}",
        f"{resolved_incidents['MTTR_Hours'].median():.2f}",
        f"{df_incident['SLA_Breached'].mean() * 100:.1f}%",
        f"{len(df_incident[df_incident['Reopen_Count'] > 0]):,} ({len(df_incident[df_incident['Reopen_Count'] > 0]) / len(df_incident) * 100:.1f}%)",
        df_incident['Closure_Code'].value_counts().index[0] if df_incident['Closure_Code'].notna().any() else 'N/A',
        df_incident['Assignment_Group'].value_counts().index[0],
        df_incident['Caller_Region'].value_counts().index[0]
    ]
}

summary_df = pd.DataFrame(summary_stats)
summary_df.to_csv(OUTPUT_DIR / 'eda_summary_stats.csv', index=False)
print(f"\nSummary Statistics:\n{summary_df.to_string(index=False)}")

# =============================================================================
# SAVE CLEANED DATA
# =============================================================================
print("\n[5] SAVING CLEANED DATASETS...")

df_service.to_pickle(OUTPUT_DIR / 'service_tasks_cleaned.pkl')
df_incident.to_pickle(OUTPUT_DIR / 'incident_dump_cleaned.pkl')

# Also save as CSV for readability
df_service.to_csv(OUTPUT_DIR / 'service_tasks_cleaned.csv', index=False)
df_incident.to_csv(OUTPUT_DIR / 'incident_dump_cleaned.csv', index=False)

print(f"  Saved cleaned Service Tasks: {OUTPUT_DIR / 'service_tasks_cleaned.pkl'}")
print(f"  Saved cleaned Incident Dump: {OUTPUT_DIR / 'incident_dump_cleaned.pkl'}")

print("\n" + "=" * 80)
print("PHASE 2 COMPLETE - Cleaning & EDA Finished")
print("=" * 80)
