"""
================================================================================
PHASE 4: CATEGORY DEEP-DIVE (AR & AP ANALYSIS)
================================================================================
AstraZeneca Cash Flow Forecasting - Datathon 2025

Purpose: Deep analysis of major cash flow categories
- AR (Accounts Receivable) - Cash inflows from customers
- AP (Accounts Payable) - Cash outflows to suppliers
- Other categories: Payroll, Tax, Loans, Netting

Business Questions:
1. What drives cash inflows vs outflows?
2. Are there seasonal patterns in AR/AP?
3. Which categories are most volatile?
4. What's the typical payment cycle?
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

from prophet import Prophet
from sklearn.metrics import mean_absolute_error
from statsmodels.tsa.seasonal import seasonal_decompose
from scipy import stats
import os

# AstraZeneca Color Palette
AZ_COLORS = {
    'mulberry': '#830051',
    'lime_green': '#C4D600',
    'navy': '#003865',
    'graphite': '#3F4444',
    'light_blue': '#68D2DF',
    'magenta': '#D0006F',
    'purple': '#3C1053',
    'gold': '#F0AB00'
}

print("=" * 80)
print("PHASE 4: CATEGORY DEEP-DIVE (AR & AP ANALYSIS)")
print("=" * 80)

# =============================================================================
# LOAD DATA
# =============================================================================
print("\n[1/8] Loading data...")

df = pd.read_csv('data_cleaned_weekly.csv')
df['Week_Start'] = pd.to_datetime(df['Week_Start'])
df = df.sort_values('Week_Start').reset_index(drop=True)

# Category columns
category_cols = {
    'AR': 'Net_Cash_AR',
    'AP': 'Net_Cash_AP',
    'Netting_AP': 'Net_Cash_Netting_AP',
    'Netting_AR': 'Net_Cash_Netting_AR',
    'Payroll': 'Net_Cash_Payroll',
    'Tax': 'Net_Cash_Tax_payable',
    'Loan_Receipt': 'Net_Cash_Loan_receipt',
    'Loan_Payment': 'Net_Cash_Loan_payment',
    'Other_Receipt': 'Net_Cash_Other_receipt'
}

print(f"   Total weeks: {len(df)}")
print(f"   Categories: {len(category_cols)}")

# =============================================================================
# CATEGORY OVERVIEW
# =============================================================================
print("\n[2/8] Category Overview...")

category_stats = []
for cat_name, col_name in category_cols.items():
    if col_name in df.columns:
        data = df[col_name]
        category_stats.append({
            'Category': cat_name,
            'Total': data.sum(),
            'Mean': data.mean(),
            'Std': data.std(),
            'Min': data.min(),
            'Max': data.max(),
            'Positive_Weeks': (data > 0).sum(),
            'Negative_Weeks': (data < 0).sum(),
            'Volatility': data.std() / abs(data.mean()) if data.mean() != 0 else np.nan
        })

stats_df = pd.DataFrame(category_stats)
stats_df = stats_df.sort_values('Total', ascending=False)

print(f"\n   CATEGORY SUMMARY (44 weeks historical):")
print(f"   +----------------+-------------+-------------+-------------+----------+")
print(f"   | Category       | Total       | Avg/Week    | Volatility  | Type     |")
print(f"   +----------------+-------------+-------------+-------------+----------+")
for _, row in stats_df.iterrows():
    cat_type = "INFLOW" if row['Total'] > 0 else "OUTFLOW"
    print(f"   | {row['Category']:<14} | ${row['Total']/1e6:>8.2f}M | ${row['Mean']/1e6:>8.2f}M | {row['Volatility']:>8.2f}x   | {cat_type:<8} |")
print(f"   +----------------+-------------+-------------+-------------+----------+")

# =============================================================================
# AR (ACCOUNTS RECEIVABLE) DEEP DIVE
# =============================================================================
print("\n[3/8] AR (Accounts Receivable) Deep Dive...")

ar_data = df[['Week_Start', 'Week_Number', 'Net_Cash_AR']].copy()
ar_data.columns = ['Week_Start', 'Week_Number', 'AR']

# AR Statistics
ar_total = ar_data['AR'].sum()
ar_mean = ar_data['AR'].mean()
ar_std = ar_data['AR'].std()
ar_positive_weeks = (ar_data['AR'] > 0).sum()

print(f"\n   AR STATISTICS:")
print(f"   +------------------------+------------------+")
print(f"   | Metric                 | Value            |")
print(f"   +------------------------+------------------+")
print(f"   | Total (44 weeks)       | ${ar_total/1e6:>12.2f}M |")
print(f"   | Average per week       | ${ar_mean/1e6:>12.2f}M |")
print(f"   | Standard Deviation     | ${ar_std/1e6:>12.2f}M |")
print(f"   | Weeks with inflow      | {ar_positive_weeks:>12} / 44 |")
print(f"   | Coefficient of Var.    | {ar_std/ar_mean:>12.2f}x |")
print(f"   +------------------------+------------------+")

# AR Prophet Model
print("\n   Building AR forecast model...")
ar_prophet_df = pd.DataFrame({
    'ds': ar_data['Week_Start'],
    'y': ar_data['AR']
})

ar_model = Prophet(
    yearly_seasonality=False,
    weekly_seasonality=False,
    daily_seasonality=False,
    seasonality_mode='additive',
    interval_width=0.95,
    changepoint_prior_scale=0.05
)
ar_model.add_seasonality(name='monthly', period=30.5, fourier_order=5)
ar_model.fit(ar_prophet_df)

# 26-week AR forecast
future_dates = pd.date_range(
    start=df['Week_Start'].max() + timedelta(weeks=1),
    periods=26,
    freq='W-MON'
)
ar_future = pd.DataFrame({'ds': future_dates})
ar_forecast = ar_model.predict(ar_future)

ar_forecast_total = ar_forecast['yhat'].sum()
print(f"   AR 26-week forecast: ${ar_forecast_total/1e6:.2f}M")

# =============================================================================
# AP (ACCOUNTS PAYABLE) DEEP DIVE
# =============================================================================
print("\n[4/8] AP (Accounts Payable) Deep Dive...")

ap_data = df[['Week_Start', 'Week_Number', 'Net_Cash_AP']].copy()
ap_data.columns = ['Week_Start', 'Week_Number', 'AP']

# AP Statistics
ap_total = ap_data['AP'].sum()
ap_mean = ap_data['AP'].mean()
ap_std = ap_data['AP'].std()
ap_negative_weeks = (ap_data['AP'] < 0).sum()

print(f"\n   AP STATISTICS:")
print(f"   +------------------------+------------------+")
print(f"   | Metric                 | Value            |")
print(f"   +------------------------+------------------+")
print(f"   | Total (44 weeks)       | ${ap_total/1e6:>12.2f}M |")
print(f"   | Average per week       | ${ap_mean/1e6:>12.2f}M |")
print(f"   | Standard Deviation     | ${ap_std/1e6:>12.2f}M |")
print(f"   | Weeks with outflow     | {ap_negative_weeks:>12} / 44 |")
print(f"   | Coefficient of Var.    | {abs(ap_std/ap_mean):>12.2f}x |")
print(f"   +------------------------+------------------+")

# AP Prophet Model
print("\n   Building AP forecast model...")
ap_prophet_df = pd.DataFrame({
    'ds': ap_data['Week_Start'],
    'y': ap_data['AP']
})

ap_model = Prophet(
    yearly_seasonality=False,
    weekly_seasonality=False,
    daily_seasonality=False,
    seasonality_mode='additive',
    interval_width=0.95,
    changepoint_prior_scale=0.05
)
ap_model.add_seasonality(name='monthly', period=30.5, fourier_order=5)
ap_model.fit(ap_prophet_df)

# 26-week AP forecast
ap_future = pd.DataFrame({'ds': future_dates})
ap_forecast = ap_model.predict(ap_future)

ap_forecast_total = ap_forecast['yhat'].sum()
print(f"   AP 26-week forecast: ${ap_forecast_total/1e6:.2f}M")

# =============================================================================
# NETTING ANALYSIS (AP & AR)
# =============================================================================
print("\n[5/8] Netting Analysis...")

netting_ap_total = df['Net_Cash_Netting_AP'].sum()
netting_ar_total = df['Net_Cash_Netting_AR'].sum()

print(f"\n   NETTING SUMMARY:")
print(f"   +------------------------+------------------+")
print(f"   | Netting Type           | Total (44 weeks) |")
print(f"   +------------------------+------------------+")
print(f"   | Netting AP             | ${netting_ap_total/1e6:>12.2f}M |")
print(f"   | Netting AR             | ${netting_ar_total/1e6:>12.2f}M |")
print(f"   | Net Netting Effect     | ${(netting_ap_total + netting_ar_total)/1e6:>12.2f}M |")
print(f"   +------------------------+------------------+")

# =============================================================================
# PAYROLL & TAX ANALYSIS
# =============================================================================
print("\n[6/8] Payroll & Tax Analysis...")

payroll_total = df['Net_Cash_Payroll'].sum()
tax_total = df['Net_Cash_Tax_payable'].sum()

# Monthly patterns
df['Month'] = df['Week_Start'].dt.month
payroll_by_month = df.groupby('Month')['Net_Cash_Payroll'].mean()
tax_by_month = df.groupby('Month')['Net_Cash_Tax_payable'].mean()

print(f"\n   PAYROLL & TAX SUMMARY:")
print(f"   +------------------------+------------------+")
print(f"   | Category               | Total (44 weeks) |")
print(f"   +------------------------+------------------+")
print(f"   | Payroll                | ${payroll_total/1e6:>12.2f}M |")
print(f"   | Tax Payable            | ${tax_total/1e6:>12.2f}M |")
print(f"   +------------------------+------------------+")

# =============================================================================
# CASH FLOW DECOMPOSITION
# =============================================================================
print("\n[7/8] Cash Flow Decomposition...")

# Total cash flow breakdown
total_cf = df['Net_Cash_Flow_USD'].sum()

cf_breakdown = {
    'AR (Receivables)': ar_total,
    'AP (Payables)': ap_total,
    'Netting AP': netting_ap_total,
    'Netting AR': netting_ar_total,
    'Payroll': payroll_total,
    'Tax': tax_total,
    'Loan Receipt': df['Net_Cash_Loan_receipt'].sum(),
    'Loan Payment': df['Net_Cash_Loan_payment'].sum(),
    'Other Receipt': df['Net_Cash_Other_receipt'].sum()
}

print(f"\n   CASH FLOW DECOMPOSITION (44 weeks):")
print(f"   +------------------------+------------------+---------+")
print(f"   | Category               | Amount           | % of CF |")
print(f"   +------------------------+------------------+---------+")

# Separate inflows and outflows
inflows = {k: v for k, v in cf_breakdown.items() if v > 0}
outflows = {k: v for k, v in cf_breakdown.items() if v < 0}

print(f"   |                        |                  |         |")
print(f"   | === INFLOWS ===        |                  |         |")
total_inflow = sum(inflows.values())
for cat, amt in sorted(inflows.items(), key=lambda x: x[1], reverse=True):
    pct = (amt / total_inflow) * 100 if total_inflow != 0 else 0
    print(f"   | {cat:<22} | ${amt/1e6:>12.2f}M | {pct:>6.1f}% |")
print(f"   | TOTAL INFLOWS          | ${total_inflow/1e6:>12.2f}M | 100.0%  |")

print(f"   |                        |                  |         |")
print(f"   | === OUTFLOWS ===       |                  |         |")
total_outflow = sum(outflows.values())
for cat, amt in sorted(outflows.items(), key=lambda x: x[1]):
    pct = (amt / total_outflow) * 100 if total_outflow != 0 else 0
    print(f"   | {cat:<22} | ${amt/1e6:>12.2f}M | {pct:>6.1f}% |")
print(f"   | TOTAL OUTFLOWS         | ${total_outflow/1e6:>12.2f}M | 100.0%  |")

print(f"   |                        |                  |         |")
print(f"   | NET CASH FLOW          | ${total_cf/1e6:>12.2f}M |         |")
print(f"   +------------------------+------------------+---------+")

# =============================================================================
# CREATE VISUALIZATIONS
# =============================================================================
print("\n[8/8] Creating visualizations...")

os.makedirs('dashboard', exist_ok=True)

# ============== FIGURE 1: CATEGORY DEEP-DIVE DASHBOARD ==============
fig = plt.figure(figsize=(22, 16))
fig.suptitle('PHASE 4: CATEGORY DEEP-DIVE\nAstraZeneca Cash Flow Forecasting', 
             fontsize=18, fontweight='bold', color=AZ_COLORS['navy'], y=0.98)

# ------ Plot 1: Category Totals (Bar Chart) ------
ax1 = fig.add_subplot(2, 3, 1)

categories = list(cf_breakdown.keys())
values = [v/1e6 for v in cf_breakdown.values()]
colors = [AZ_COLORS['lime_green'] if v > 0 else AZ_COLORS['magenta'] for v in values]

bars = ax1.barh(categories, values, color=colors, edgecolor=AZ_COLORS['navy'], linewidth=1.5)
ax1.axvline(x=0, color=AZ_COLORS['graphite'], linewidth=2)
ax1.set_xlabel('Total (Millions USD)', fontweight='bold')
ax1.set_title('Category Totals (44 Weeks Historical)\nGreen=Inflow, Magenta=Outflow', fontweight='bold', fontsize=11)

for bar, val in zip(bars, values):
    x_pos = val + 1 if val > 0 else val - 1
    ha = 'left' if val > 0 else 'right'
    ax1.text(x_pos, bar.get_y() + bar.get_height()/2, f'${val:.1f}M', 
             ha=ha, va='center', fontweight='bold', fontsize=9)

ax1.grid(True, alpha=0.3, axis='x')

# ------ Plot 2: AR vs AP Timeline ------
ax2 = fig.add_subplot(2, 3, 2)

weeks = df['Week_Number'].values
ax2.plot(weeks, df['Net_Cash_AR']/1e6, 'o-', color=AZ_COLORS['lime_green'], 
         linewidth=2, markersize=5, label='AR (Receivables)', alpha=0.8)
ax2.plot(weeks, df['Net_Cash_AP']/1e6, 's-', color=AZ_COLORS['magenta'], 
         linewidth=2, markersize=5, label='AP (Payables)', alpha=0.8)
ax2.axhline(y=0, color=AZ_COLORS['graphite'], linewidth=1, linestyle='--')

ax2.set_xlabel('Week Number', fontweight='bold')
ax2.set_ylabel('Cash Flow (Millions USD)', fontweight='bold')
ax2.set_title('AR vs AP Weekly Cash Flow', fontweight='bold', fontsize=11)
ax2.legend()
ax2.grid(True, alpha=0.3)

# ------ Plot 3: AR Forecast ------
ax3 = fig.add_subplot(2, 3, 3)

# Historical
ax3.plot(weeks, df['Net_Cash_AR']/1e6, 'o-', color=AZ_COLORS['navy'], 
         linewidth=2, markersize=5, label='Historical', alpha=0.8)

# Forecast
forecast_weeks = list(range(45, 71))
ax3.plot(forecast_weeks, ar_forecast['yhat']/1e6, 'o-', color=AZ_COLORS['lime_green'], 
         linewidth=2, markersize=5, label='Forecast')
ax3.fill_between(forecast_weeks, ar_forecast['yhat_lower']/1e6, ar_forecast['yhat_upper']/1e6,
                 color=AZ_COLORS['lime_green'], alpha=0.2)

ax3.axvline(x=44.5, color=AZ_COLORS['mulberry'], linestyle='--', linewidth=2)
ax3.axhline(y=0, color=AZ_COLORS['graphite'], linewidth=1, linestyle='--')

ax3.set_xlabel('Week Number', fontweight='bold')
ax3.set_ylabel('AR Cash Flow (Millions USD)', fontweight='bold')
ax3.set_title(f'AR Forecast (26 weeks: ${ar_forecast_total/1e6:.1f}M)', fontweight='bold', fontsize=11)
ax3.legend()
ax3.grid(True, alpha=0.3)

# ------ Plot 4: AP Forecast ------
ax4 = fig.add_subplot(2, 3, 4)

# Historical
ax4.plot(weeks, df['Net_Cash_AP']/1e6, 's-', color=AZ_COLORS['navy'], 
         linewidth=2, markersize=5, label='Historical', alpha=0.8)

# Forecast
ax4.plot(forecast_weeks, ap_forecast['yhat']/1e6, 's-', color=AZ_COLORS['magenta'], 
         linewidth=2, markersize=5, label='Forecast')
ax4.fill_between(forecast_weeks, ap_forecast['yhat_lower']/1e6, ap_forecast['yhat_upper']/1e6,
                 color=AZ_COLORS['magenta'], alpha=0.2)

ax4.axvline(x=44.5, color=AZ_COLORS['mulberry'], linestyle='--', linewidth=2)
ax4.axhline(y=0, color=AZ_COLORS['graphite'], linewidth=1, linestyle='--')

ax4.set_xlabel('Week Number', fontweight='bold')
ax4.set_ylabel('AP Cash Flow (Millions USD)', fontweight='bold')
ax4.set_title(f'AP Forecast (26 weeks: ${ap_forecast_total/1e6:.1f}M)', fontweight='bold', fontsize=11)
ax4.legend()
ax4.grid(True, alpha=0.3)

# ------ Plot 5: Cash Flow Composition Pie Chart ------
ax5 = fig.add_subplot(2, 3, 5)

# Separate inflows and outflows for pie
pie_data = {
    'AR': ar_total,
    'Other Inflows': total_inflow - ar_total,
    'AP': abs(ap_total),
    'Netting': abs(netting_ap_total + netting_ar_total),
    'Payroll': abs(payroll_total),
    'Tax': abs(tax_total),
    'Other Outflows': abs(total_outflow) - abs(ap_total) - abs(netting_ap_total + netting_ar_total) - abs(payroll_total) - abs(tax_total)
}

# Filter out small/negative values
pie_data = {k: v for k, v in pie_data.items() if v > 0}

pie_colors = [AZ_COLORS['lime_green'], AZ_COLORS['light_blue'], 
              AZ_COLORS['magenta'], AZ_COLORS['purple'], 
              AZ_COLORS['gold'], AZ_COLORS['mulberry'], AZ_COLORS['graphite']][:len(pie_data)]

wedges, texts, autotexts = ax5.pie(pie_data.values(), labels=pie_data.keys(), autopct='%1.0f%%',
                                    colors=pie_colors, explode=[0.05]*len(pie_data),
                                    textprops={'fontsize': 9})
ax5.set_title('Cash Flow Composition by Category', fontweight='bold', fontsize=11)

# ------ Plot 6: Summary Statistics ------
ax6 = fig.add_subplot(2, 3, 6)
ax6.axis('off')

summary_text = f"""
CATEGORY DEEP-DIVE SUMMARY
==========================

AR (ACCOUNTS RECEIVABLE)
------------------------
Historical Total:    ${ar_total/1e6:>10.2f}M
Average per Week:    ${ar_mean/1e6:>10.2f}M
26-Week Forecast:    ${ar_forecast_total/1e6:>10.2f}M
Business Insight:    Primary cash inflow source
                     Customer payments collected

AP (ACCOUNTS PAYABLE)
---------------------
Historical Total:    ${ap_total/1e6:>10.2f}M
Average per Week:    ${ap_mean/1e6:>10.2f}M
26-Week Forecast:    ${ap_forecast_total/1e6:>10.2f}M
Business Insight:    Main cash outflow driver
                     Supplier payments made

NETTING OPERATIONS
------------------
Netting AP Total:    ${netting_ap_total/1e6:>10.2f}M
Netting AR Total:    ${netting_ar_total/1e6:>10.2f}M
Net Effect:          ${(netting_ap_total + netting_ar_total)/1e6:>10.2f}M
Business Insight:    Intercompany settlements

OTHER CATEGORIES
----------------
Payroll:             ${payroll_total/1e6:>10.2f}M
Tax:                 ${tax_total/1e6:>10.2f}M
Loan Receipts:       ${df['Net_Cash_Loan_receipt'].sum()/1e6:>10.2f}M
Loan Payments:       ${df['Net_Cash_Loan_payment'].sum()/1e6:>10.2f}M

KEY INSIGHT
-----------
AR drives inflows ({ar_total/total_inflow*100:.0f}% of inflows)
Netting drives outflows
({abs(netting_ap_total)/abs(total_outflow)*100:.0f}% of outflows)
"""

ax6.text(0.05, 0.95, summary_text, transform=ax6.transAxes, fontsize=9,
         verticalalignment='top', fontfamily='monospace',
         bbox=dict(boxstyle='round', facecolor=AZ_COLORS['light_blue'], alpha=0.2))

plt.tight_layout()
plt.savefig('dashboard/06_category_deep_dive.png', dpi=300, bbox_inches='tight', facecolor='white')
plt.close()

print("   Saved: dashboard/06_category_deep_dive.png")

# ============== FIGURE 2: AR/AP DETAILED ANALYSIS ==============
fig2, axes = plt.subplots(2, 2, figsize=(16, 12))
fig2.suptitle('AR & AP Detailed Analysis\nAstraZeneca Cash Flow Forecasting', 
              fontsize=14, fontweight='bold', color=AZ_COLORS['navy'])

# Plot 1: AR Distribution
ax = axes[0, 0]
ax.hist(df['Net_Cash_AR']/1e6, bins=20, color=AZ_COLORS['lime_green'], 
        edgecolor=AZ_COLORS['navy'], alpha=0.7)
ax.axvline(x=ar_mean/1e6, color=AZ_COLORS['mulberry'], linestyle='--', linewidth=2, 
           label=f'Mean: ${ar_mean/1e6:.1f}M')
ax.set_xlabel('AR Weekly Cash Flow (Millions USD)', fontweight='bold')
ax.set_ylabel('Frequency', fontweight='bold')
ax.set_title('AR Distribution', fontweight='bold')
ax.legend()

# Plot 2: AP Distribution
ax = axes[0, 1]
ax.hist(df['Net_Cash_AP']/1e6, bins=20, color=AZ_COLORS['magenta'], 
        edgecolor=AZ_COLORS['navy'], alpha=0.7)
ax.axvline(x=ap_mean/1e6, color=AZ_COLORS['mulberry'], linestyle='--', linewidth=2, 
           label=f'Mean: ${ap_mean/1e6:.1f}M')
ax.set_xlabel('AP Weekly Cash Flow (Millions USD)', fontweight='bold')
ax.set_ylabel('Frequency', fontweight='bold')
ax.set_title('AP Distribution', fontweight='bold')
ax.legend()

# Plot 3: AR vs Total Cash Flow Correlation
ax = axes[1, 0]
ax.scatter(df['Net_Cash_AR']/1e6, df['Net_Cash_Flow_USD']/1e6, 
           c=AZ_COLORS['navy'], s=80, alpha=0.6, edgecolors='white')
# Add trend line
z = np.polyfit(df['Net_Cash_AR'], df['Net_Cash_Flow_USD'], 1)
p = np.poly1d(z)
ax.plot(df['Net_Cash_AR']/1e6, p(df['Net_Cash_AR'])/1e6, '--', 
        color=AZ_COLORS['magenta'], linewidth=2, label=f'Trend')
corr_ar = df['Net_Cash_AR'].corr(df['Net_Cash_Flow_USD'])
ax.set_xlabel('AR Cash Flow (Millions USD)', fontweight='bold')
ax.set_ylabel('Total Cash Flow (Millions USD)', fontweight='bold')
ax.set_title(f'AR vs Total Cash Flow (Corr: {corr_ar:.2f})', fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)

# Plot 4: AP vs Total Cash Flow Correlation
ax = axes[1, 1]
ax.scatter(df['Net_Cash_AP']/1e6, df['Net_Cash_Flow_USD']/1e6, 
           c=AZ_COLORS['navy'], s=80, alpha=0.6, edgecolors='white')
z = np.polyfit(df['Net_Cash_AP'], df['Net_Cash_Flow_USD'], 1)
p = np.poly1d(z)
ax.plot(df['Net_Cash_AP']/1e6, p(df['Net_Cash_AP'])/1e6, '--', 
        color=AZ_COLORS['lime_green'], linewidth=2, label=f'Trend')
corr_ap = df['Net_Cash_AP'].corr(df['Net_Cash_Flow_USD'])
ax.set_xlabel('AP Cash Flow (Millions USD)', fontweight='bold')
ax.set_ylabel('Total Cash Flow (Millions USD)', fontweight='bold')
ax.set_title(f'AP vs Total Cash Flow (Corr: {corr_ap:.2f})', fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig('dashboard/06_ar_ap_detailed.png', dpi=300, bbox_inches='tight', facecolor='white')
plt.close()

print("   Saved: dashboard/06_ar_ap_detailed.png")

# =============================================================================
# SAVE RESULTS
# =============================================================================
print("\n   Saving results...")

# Category summary
stats_df.to_csv('category_analysis_summary.csv', index=False)
print("   Saved: category_analysis_summary.csv")

# AR forecast
ar_forecast_output = ar_forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].copy()
ar_forecast_output.columns = ['Week_Start', 'AR_Forecast', 'AR_Lower_95', 'AR_Upper_95']
ar_forecast_output.to_csv('ar_forecast_26weeks.csv', index=False)
print("   Saved: ar_forecast_26weeks.csv")

# AP forecast
ap_forecast_output = ap_forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].copy()
ap_forecast_output.columns = ['Week_Start', 'AP_Forecast', 'AP_Lower_95', 'AP_Upper_95']
ap_forecast_output.to_csv('ap_forecast_26weeks.csv', index=False)
print("   Saved: ap_forecast_26weeks.csv")

# =============================================================================
# FINAL SUMMARY
# =============================================================================
print("\n" + "=" * 80)
print("PHASE 4 COMPLETE: CATEGORY DEEP-DIVE")
print("=" * 80)

print(f"""
CATEGORY ANALYSIS SUMMARY
=========================

MAJOR INFLOWS (Historical 44 weeks):
   +------------------------+---------------+----------+
   | Category               | Total         | % Share  |
   +------------------------+---------------+----------+
   | AR (Receivables)       | ${ar_total/1e6:>10.2f}M | {ar_total/total_inflow*100:>6.1f}%  |
   | Loan Receipts          | ${df['Net_Cash_Loan_receipt'].sum()/1e6:>10.2f}M | {df['Net_Cash_Loan_receipt'].sum()/total_inflow*100:>6.1f}%  |
   | Other Receipts         | ${df['Net_Cash_Other_receipt'].sum()/1e6:>10.2f}M | {df['Net_Cash_Other_receipt'].sum()/total_inflow*100:>6.1f}%  |
   +------------------------+---------------+----------+
   | TOTAL INFLOWS          | ${total_inflow/1e6:>10.2f}M | 100.0%  |
   +------------------------+---------------+----------+

MAJOR OUTFLOWS (Historical 44 weeks):
   +------------------------+---------------+----------+
   | Category               | Total         | % Share  |
   +------------------------+---------------+----------+
   | AP (Payables)          | ${ap_total/1e6:>10.2f}M | {abs(ap_total)/abs(total_outflow)*100:>6.1f}%  |
   | Netting AP             | ${netting_ap_total/1e6:>10.2f}M | {abs(netting_ap_total)/abs(total_outflow)*100:>6.1f}%  |
   | Payroll                | ${payroll_total/1e6:>10.2f}M | {abs(payroll_total)/abs(total_outflow)*100:>6.1f}%  |
   | Tax                    | ${tax_total/1e6:>10.2f}M | {abs(tax_total)/abs(total_outflow)*100:>6.1f}%  |
   +------------------------+---------------+----------+
   | TOTAL OUTFLOWS         | ${total_outflow/1e6:>10.2f}M | 100.0%  |
   +------------------------+---------------+----------+

26-WEEK FORECASTS:
   AR Forecast:  ${ar_forecast_total/1e6:>10.2f}M (expected inflows)
   AP Forecast:  ${ap_forecast_total/1e6:>10.2f}M (expected outflows)
   Net AR - AP:  ${(ar_forecast_total + ap_forecast_total)/1e6:>10.2f}M

CORRELATIONS WITH TOTAL CASH FLOW:
   AR correlation: {corr_ar:.2f} ({'Strong' if abs(corr_ar) > 0.5 else 'Moderate' if abs(corr_ar) > 0.3 else 'Weak'})
   AP correlation: {corr_ap:.2f} ({'Strong' if abs(corr_ap) > 0.5 else 'Moderate' if abs(corr_ap) > 0.3 else 'Weak'})

KEY BUSINESS INSIGHTS:
   1. AR dominates inflows ({ar_total/total_inflow*100:.0f}% of all inflows)
   2. Netting AP dominates outflows ({abs(netting_ap_total)/abs(total_outflow)*100:.0f}% of all outflows)
   3. Payroll and Tax are predictable recurring outflows
   4. Net cash position driven by AR collection timing

FILES CREATED:
   - dashboard/06_category_deep_dive.png
   - dashboard/06_ar_ap_detailed.png
   - category_analysis_summary.csv
   - ar_forecast_26weeks.csv
   - ap_forecast_26weeks.csv

==> PHASE 4 COMPLETE! Ready for Phase 5 (Dashboards) or Phase 8 (Documentation).
""")

