import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np


def plot_sliding_window(
        scores,
        indices,
        file_name,
        window_size,
        expected_boundaries=None
):
    plt.figure(figsize=(14, 5))

    plt.bar(indices, scores, label="Cosine similarity")

    threshold = np.mean(scores) - 1.2 * np.std(scores)
    plt.axhline(
        threshold,
        color="red",
        linestyle="--",
        label="Threshold"
    )


    for i, s in zip(indices, scores):
        if s < threshold:
            plt.scatter(i, s, color="red", zorder=3)


    if expected_boundaries:
        for b in expected_boundaries:
            plt.axvline(
                b,
                color="green",
                linestyle=":",
                alpha=0.7,
                label="Expected boundary" if b == expected_boundaries[0] else None
            )

    ax = plt.gca()  # get current axis
    import matplotlib.ticker as mticker
    ax.xaxis.set_major_locator(mticker.MultipleLocator(1))

    plt.xlabel("index of block (between i-1 and i)")
    plt.ylabel("Semantic similarity")
    plt.title(f"Sliding Window Topic Segmentation with window size {window_size}")
    plt.legend()
    plt.tight_layout()

    p = Path(file_name)
    if p.parent:  # only if there's a directory component
        p.parent.mkdir(parents=True, exist_ok=True)

    plt.savefig(file_name)
    plt.close()
