using ClaudeDo.Data;
using ClaudeDo.Data.Models;

namespace ClaudeDo.Worker.Refine;

public static class RefinePrompt
{
    public const string GetTaskTool = "mcp__claudedo__get_task";
    public const string UpdateTaskTool = "mcp__claudedo__update_task";
    public const string AddSubtaskTool = "mcp__claudedo__add_subtask";

    public static string LogPath(string taskId) =>
        System.IO.Path.Combine(Paths.AppDataRoot(), "logs", $"refine-{Short(taskId)}.log");

    public static IReadOnlyList<string> BuildArgs(int maxTurns, bool canReadRepo)
    {
        var args = new List<string>
        {
            "-p", "--output-format", "stream-json", "--verbose",
            "--permission-mode", "acceptEdits",
            "--max-turns", maxTurns.ToString(),
            "--allowedTools", GetTaskTool, UpdateTaskTool, AddSubtaskTool,
        };
        if (canReadRepo)
        {
            args.Add("Read");
            args.Add("Grep");
            args.Add("Glob");
        }
        return args;
    }

    public static string BuildPrompt(TaskEntity task, IEnumerable<SubtaskEntity> subtasks)
    {
        var open = subtasks.Where(s => !s.Completed).Select(s => $"- {s.Title}").ToList();
        var subText = open.Count == 0 ? "(none)" : string.Join("\n", open);
        return PromptFiles.Render(PromptKind.Refine, new Dictionary<string, string>
        {
            ["taskId"] = task.Id,
            ["title"] = task.Title,
            ["description"] = string.IsNullOrWhiteSpace(task.Description) ? "(empty)" : task.Description!,
            ["subtasks"] = subText,
        });
    }

    private static string Short(string id) => id.Length >= 8 ? id[..8] : id;
}
