using Markdig;
using YamlDotNet.Serialization;

namespace CarneiroTech.Services;

public class MarkdownService : IMarkdownService
{
    private readonly MarkdownPipeline _pipeline;

    public MarkdownService()
    {
        _pipeline = new MarkdownPipelineBuilder()
            .UseAdvancedExtensions()
            .Build();
    }

    public string ConvertToHtml(string markdown)
    {
        return Markdown.ToHtml(markdown, _pipeline);
    }

    public Dictionary<string, object> ParseFrontMatter(string content, out string bodyContent)
    {
        bodyContent = content;
        var frontMatter = new Dictionary<string, object>();

        if (!content.StartsWith("---"))
        {
            return frontMatter;
        }

        var lines = content.Split('\n');
        var yamlLines = new List<string>();
        var bodyLines = new List<string>();
        var inFrontMatter = false;
        var frontMatterEnded = false;

        for (int i = 0; i < lines.Length; i++)
        {
            var line = lines[i];

            if (i == 0 && line.Trim() == "---")
            {
                inFrontMatter = true;
                continue;
            }

            if (inFrontMatter && line.Trim() == "---")
            {
                inFrontMatter = false;
                frontMatterEnded = true;
                continue;
            }

            if (inFrontMatter)
            {
                yamlLines.Add(line);
            }
            else if (frontMatterEnded)
            {
                bodyLines.Add(line);
            }
        }

        if (yamlLines.Any())
        {
            var yaml = string.Join("\n", yamlLines);
            var deserializer = new DeserializerBuilder().Build();
            frontMatter = deserializer.Deserialize<Dictionary<string, object>>(yaml)
                          ?? new Dictionary<string, object>();
        }

        bodyContent = string.Join("\n", bodyLines).Trim();
        return frontMatter;
    }
}
