"""
plot_confusion_matrix:
Compute and plot a confusion matrix (counts or normalized).
"""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.metrics import confusion_matrix
from typing import Sequence, Optional

def plot_confusion_matrix(y_true: Sequence, y_pred: Sequence,
                          labels: Optional[Sequence] = None,
                          normalize: bool = False,
                          title: Optional[str] = None,
                          show: bool = True,
                          save_path: Optional[str] = None):
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    if normalize:
        row_sums = cm.sum(axis=1, keepdims=True)
        row_sums[row_sums == 0] = 1
        cm_display = cm / row_sums
    else:
        cm_display = cm

    plt.figure(figsize=(7, 5))
    sns.heatmap(cm_display, annot=True, fmt=".2f" if normalize else "d",
                cmap="Blues", xticklabels=labels, yticklabels=labels)
    plt.ylabel("True label")
    plt.xlabel("Predicted label")
    if title:
        plt.title(title)
    plt.tight_layout()
    if save_path:
        plt.savefig(save_path)
    if show:
        plt.show()
    plt.close()
