using System.Text;

namespace PlotLine.Services;

public static class StoryIntelligenceParagraphs
{
    public static IReadOnlyList<string> Split(string? chapterText)
        => NormalizeLineEndings(chapterText)
            .Split('\n', StringSplitOptions.RemoveEmptyEntries)
            .Select(paragraph => paragraph.Trim())
            .Where(paragraph => !string.IsNullOrWhiteSpace(paragraph))
            .ToList();

    public static string Number(IReadOnlyList<string> paragraphs)
    {
        var builder = new StringBuilder();
        for (var index = 0; index < paragraphs.Count; index++)
        {
            if (index > 0)
            {
                builder.AppendLine();
                builder.AppendLine();
            }

            builder.Append('[')
                .Append(index + 1)
                .Append("] ")
                .Append(paragraphs[index]);
        }

        return builder.ToString();
    }

    private static string NormalizeLineEndings(string? value)
        => (value ?? string.Empty)
            .Replace("\r\n", "\n", StringComparison.Ordinal)
            .Replace('\r', '\n')
            .Replace('\v', '\n')
            .Replace('\f', '\n')
            .Replace('\u2028', '\n')
            .Replace('\u2029', '\n');
}
