using System.Globalization;
using System.Text;

namespace ClaudeDo.Worker.Report;

public static class WeekReportPromptBuilder
{
    public static string Build(
        DateOnly start, DateOnly end,
        IReadOnlyList<RepoActivity> activity,
        IReadOnlyDictionary<DateOnly, List<string>> notesByDay)
    {
        var sb = new StringBuilder();
        sb.AppendLine(ClaudeDo.Data.PromptFiles.Render(
            ClaudeDo.Data.PromptKind.WeeklyReport,
            new Dictionary<string, string>
            {
                ["start"] = start.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture),
                ["end"] = end.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture),
            }));
        sb.AppendLine();

        var days = new SortedDictionary<DateOnly, List<(string Repo, DayActivity Day)>>();
        foreach (var repo in activity)
            foreach (var day in repo.Days)
            {
                if (!days.TryGetValue(day.Date, out var list))
                    days[day.Date] = list = new();
                list.Add((repo.RepoPath, day));
            }
        foreach (var d in notesByDay.Keys)
            if (!days.ContainsKey(d)) days[d] = new();

        sb.AppendLine("== Activity (from session history) ==");
        foreach (var (date, repos) in days)
        {
            sb.AppendLine($"### {date:yyyy-MM-dd}");
            foreach (var (repoPath, day) in repos)
            {
                sb.AppendLine($"Repo: {repoPath}");
                foreach (var p in day.Prompts) sb.AppendLine($"  Prompt: {p}");
                foreach (var s in day.Summaries) sb.AppendLine($"  Summary: {s}");
            }
            sb.AppendLine();
        }

        sb.AppendLine("== Developer notes ==");
        foreach (var (date, _) in days)
        {
            if (!notesByDay.TryGetValue(date, out var notes) || notes.Count == 0) continue;
            sb.AppendLine($"### {date:yyyy-MM-dd}");
            foreach (var n in notes) sb.AppendLine($"  - {n}");
        }

        return sb.ToString();
    }
}
