using System.Collections.Generic;
using System.Text;

namespace CounterDrone.Core.Reporting
{
    /// <summary>从 ReportData 渲染 Markdown 文本</summary>
    public class MarkdownRenderer
    {
        public string Render(ReportData data)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"# {data.Title}");
            sb.AppendLine();
            AppendKeyValueTable(sb, "项目", "值", data.Header);
            sb.AppendLine();

            foreach (var section in data.Sections)
            {
                sb.AppendLine($"## {section.Title}");
                sb.AppendLine();
                foreach (var block in section.Blocks)
                    RenderBlock(sb, block);
                sb.AppendLine();
            }

            return sb.ToString();
        }

        private void RenderBlock(StringBuilder sb, ReportBlock block)
        {
            switch (block)
            {
                case KeyValueBlock kv:
                    AppendKeyValueTable(sb, kv.LabelHeader, kv.ValueHeader, kv.Items);
                    sb.AppendLine();
                    break;
                case TableBlock tb:
                    if (!string.IsNullOrEmpty(tb.Caption))
                    {
                        sb.AppendLine($"### {tb.Caption}");
                        sb.AppendLine();
                    }
                    AppendTable(sb, tb.Headers, tb.Rows);
                    sb.AppendLine();
                    break;
                case TextBlock text:
                    if (text.Bold)
                        sb.AppendLine($"**{text.Text}**");
                    else
                        sb.AppendLine(text.Text);
                    sb.AppendLine();
                    break;
            }
        }

        private static void AppendKeyValueTable(StringBuilder sb, string labelHeader, string valueHeader, List<MetaItem> items)
        {
            sb.AppendLine($"| {labelHeader} | {valueHeader} |");
            sb.AppendLine($"|{new string('-', labelHeader.Length + 2)}|{new string('-', valueHeader.Length + 2)}|");
            foreach (var item in items)
                sb.AppendLine($"| {item.Label} | {item.Value} |");
        }

        private static void AppendTable(StringBuilder sb, string[] headers, List<string[]> rows)
        {
            sb.AppendLine($"| {string.Join(" | ", headers)} |");
            sb.AppendLine($"|{string.Join("|", RepeatEach(headers, h => new string('-', h.Length + 2)))}|");
            foreach (var row in rows)
                sb.AppendLine($"| {string.Join(" | ", row)} |");
        }

        private static IEnumerable<string> RepeatEach(string[] source, System.Func<string, string> fn)
        {
            foreach (var s in source)
                yield return fn(s);
        }
    }
}
