import os
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')  # Use non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
from pimenet.logger import get_logger
from pimenet.config import config

logger = get_logger(__name__)

def plot_training_history(train_losses, val_losses, train_accuracies, val_accuracies, 
                          overall_train_losses, overall_val_losses, 
                          overall_train_accuracies, overall_val_accuracies, model_suffix, save_path=None):
    """Plot training history with overall metrics"""
    
    # Guard against empty data
    if not train_losses or not val_losses:
        logger.warning("No training data available for plotting")
        return
    
    # Create figure with subplots
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))
    
    # Overall Loss Plot
    axes[0, 0].plot(train_losses, label='Train Loss', color='blue', linewidth=2)
    axes[0, 0].plot(val_losses, label='Val Loss', color='red', linewidth=2)
    axes[0, 0].set_xlabel('Epoch')
    axes[0, 0].set_ylabel('Loss')
    axes[0, 0].set_title('Overall Loss')
    axes[0, 0].legend()
    axes[0, 0].grid(True, alpha=0.3)
    
    # Overall Accuracy Plot
    if overall_train_accuracies and overall_val_accuracies:
        axes[0, 1].plot(overall_train_accuracies, label='Train Acc', color='blue', linewidth=2)
        axes[0, 1].plot(overall_val_accuracies, label='Val Acc', color='red', linewidth=2)
        axes[0, 1].set_xlabel('Epoch')
        axes[0, 1].set_ylabel('Accuracy')
        axes[0, 1].set_title('Overall Accuracy')
        axes[0, 1].legend()
        axes[0, 1].grid(True, alpha=0.3)
    else:
        axes[0, 1].text(0.5, 0.5, 'No overall accuracy data', 
                       ha='center', va='center', transform=axes[0, 1].transAxes)
        axes[0, 1].set_title('Overall Accuracy')
    
    # Per-task Accuracy Plot
    for task in train_accuracies.keys():
        if task in train_accuracies and len(train_accuracies[task]) > 0:
            axes[1, 0].plot(train_accuracies[task], label=f'{task} Train', alpha=0.7, linewidth=2)
            axes[1, 0].plot(val_accuracies[task], label=f'{task} Val', alpha=0.7, linewidth=2)
    axes[1, 0].set_xlabel('Epoch')
    axes[1, 0].set_ylabel('Accuracy')
    axes[1, 0].set_title('Per-Task Accuracy')
    axes[1, 0].legend()
    axes[1, 0].grid(True, alpha=0.3)
    
    # Final metrics table
    axes[1, 1].axis('off')
    final_metrics = f"""
    Final Training Results:
    
    Best Val Loss: {min(val_losses):.4f}
    Best Overall Acc: {max(overall_val_accuracies) if overall_val_accuracies else 'N/A'}
    
    Per-Task Best Accuracies:
    """
    for task in val_accuracies.keys():
        if task in val_accuracies and len(val_accuracies[task]) > 0:
            best_task_acc = max(val_accuracies[task])
            final_metrics += f"{task}: {best_task_acc:.4f}\n"
    
    axes[1, 1].text(0.1, 0.9, final_metrics, transform=axes[1, 1].transAxes, 
                   fontsize=10, verticalalignment='top', fontfamily='monospace')
    
    plt.tight_layout()
    
    # Save plot if save_path is provided
    if save_path:
        plt.savefig(save_path, dpi=400, bbox_inches='tight')
        logger.info(f"Training plots saved to: {save_path}")
    else:
        default_path = os.path.join(config.plots_dir, f'training_history{model_suffix}.png')
        plt.savefig(default_path, dpi=400, bbox_inches='tight')
        logger.info(f"Training plots saved to: {default_path}")
    
    # Close the plot
    plt.close()
    logger.info("Training plots saved and closed")

def plot_simple_accuracy_loss(train_losses, val_losses, overall_train_accuracies, overall_val_accuracies, 
                             model_suffix, save_path=None):
    """Create a simple accuracy and loss plot with 400 DPI."""
    try:
        # Guard against empty data
        if not train_losses or not val_losses:
            logger.warning("No training data available for simple plotting")
            return False
        
        # Create figure with 2 subplots side by side
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
        
        # Loss plot (left)
        ax1.plot(train_losses, label='Train Loss', color='#2E86AB', linewidth=2.5)
        ax1.plot(val_losses, label='Val Loss', color='#C73E1D', linewidth=2.5)
        ax1.set_xlabel('Epoch', fontsize=12, fontweight='bold')
        ax1.set_ylabel('Loss', fontsize=12, fontweight='bold')
        ax1.set_title('Training & Validation Loss', fontsize=14, fontweight='bold', pad=20)
        ax1.legend(fontsize=10)
        ax1.grid(True, alpha=0.3, linestyle='--')
        ax1.set_axisbelow(True)
        
        # Accuracy plot (right)
        if overall_train_accuracies and overall_val_accuracies:
            # Convert to percentages
            train_acc_pct = [acc * 100 for acc in overall_train_accuracies]
            val_acc_pct = [acc * 100 for acc in overall_val_accuracies]
            
            ax2.plot(train_acc_pct, label='Train Accuracy', color='#2E86AB', linewidth=2.5)
            ax2.plot(val_acc_pct, label='Val Accuracy', color='#C73E1D', linewidth=2.5)
            ax2.set_xlabel('Epoch', fontsize=12, fontweight='bold')
            ax2.set_ylabel('Accuracy (%)', fontsize=12, fontweight='bold')
            ax2.set_title('Training & Validation Accuracy', fontsize=14, fontweight='bold', pad=20)
            ax2.legend(fontsize=10)
            ax2.grid(True, alpha=0.3, linestyle='--')
            ax2.set_axisbelow(True)
            ax2.set_ylim(0, 100)
        else:
            ax2.text(0.5, 0.5, 'No accuracy data available', 
                    ha='center', va='center', transform=ax2.transAxes,
                    fontsize=12, fontweight='bold')
            ax2.set_title('Training & Validation Accuracy', fontsize=14, fontweight='bold', pad=20)
        
        # Style improvements
        for ax in [ax1, ax2]:
            ax.tick_params(axis='both', labelsize=10)
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
        
        plt.tight_layout()
        
        # Save with 400 DPI
        simple_save_path = save_path.replace('.png', '_simple.png') if save_path else os.path.join(config.plots_dir, f'training_simple{model_suffix}.png')
        plt.savefig(simple_save_path, dpi=400, bbox_inches='tight', 
                   facecolor='white', edgecolor='none')
        plt.close()
        
        logger.info(f"Simple training plot saved to: {simple_save_path} (400 DPI)")
        return True
        
    except Exception as e:
        logger.error(f"Failed to create simple training plot: {e}")
        return False

def plot_confusion_matrix(all_labels, final_predictions, output_file="confusion_matrix.png"):
    """Create and save a confusion matrix with 400 DPI."""
    try:
        # Resolve class mapping file path dynamically based on dataset configuration
        dataset_type = getattr(config.dataset, 'dataset_type', '100d').lower()
        class_to_idx_file_name = "class_to_idx_100d.json" if dataset_type == "100d" else "class_to_idx_3pdd.json"
        class_to_idx_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), class_to_idx_file_name)
        class_names = []
        
        try:
            with open(class_to_idx_file, 'r') as f:
                class_to_idx = json.load(f)
                idx_to_class = {v: k for k, v in class_to_idx.items()}
                # Sort by index to ensure correct order
                max_idx = max(idx_to_class.keys())
                class_names = [idx_to_class.get(i, f'class_{i}') for i in range(max_idx + 1)]
        except Exception as e:
            logger.warning(f"Could not load class names: {e}")
            # Fallback to generic class names
            max_label = max(max(all_labels), max(final_predictions))
            class_names = [f'class_{i}' for i in range(int(max_label) + 1)]
        
        # Create confusion matrix
        cm = confusion_matrix(all_labels, final_predictions)
        
        # Create figure
        plt.figure(figsize=(10, 8))
        
        # Create heatmap
        sns.heatmap(cm, 
                   annot=True, 
                   fmt='d', 
                   cmap='Blues',
                   xticklabels=class_names,
                   yticklabels=class_names,
                   cbar_kws={'shrink': 0.8})
        
        plt.title('Confusion Matrix - PIMENet Test Results', 
                 fontsize=16, fontweight='bold', pad=20)
        plt.xlabel('Predicted Class', fontsize=12, fontweight='bold')
        plt.ylabel('True Class', fontsize=12, fontweight='bold')
        
        # Rotate labels for better readability
        plt.xticks(rotation=45, ha='right')
        plt.yticks(rotation=0)
        
        # Tight layout
        plt.tight_layout()
        
        # Save with 400 DPI
        plt.savefig(output_file, dpi=400, bbox_inches='tight', 
                   facecolor='white', edgecolor='none')
        plt.close()
        
        logger.info(f"Confusion matrix saved to: {output_file} (400 DPI)")
        
        # Print confusion matrix statistics
        total_samples = len(all_labels)
        correct_predictions = np.trace(cm)
        logger.info("Confusion Matrix Stats:")
        logger.info(f"   Total Samples: {total_samples}")
        logger.info(f"   Correct Predictions: {correct_predictions}")
        logger.info(f"   Accuracy: {correct_predictions/total_samples:.4f}")
        
        return True
        
    except Exception as e:
        logger.error(f"Failed to create confusion matrix: {e}")
        return False
