using Sdt.Config;

namespace Sdt.Core;

public sealed record DoctorAutoFixResult(
    bool Success,
    string Message,
    int CreatedDirectories = 0,
    string? BackupPath = null);

public sealed class ConfigDoctorAutoFixService
{
    public IReadOnlyList<string> FindMissingWorkingDirectories(DevToolConfig config, string projectRoot)
    {
        var missing = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        foreach (var workflow in config.Workflows)
        {
            foreach (var step in workflow.Steps)
            {
                if (string.IsNullOrWhiteSpace(step.WorkingDir))
                    continue;
                var path = Path.GetFullPath(Path.Combine(projectRoot, step.WorkingDir));
                if (!Directory.Exists(path))
                    missing.Add(path);
            }
        }

        return missing.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList();
    }

    public DoctorAutoFixResult CreateMissingWorkingDirectories(IReadOnlyList<string> directories)
    {
        var created = 0;
        try
        {
            foreach (var dir in directories)
            {
                if (Directory.Exists(dir))
                    continue;
                Directory.CreateDirectory(dir);
                created++;
            }

            return new DoctorAutoFixResult(
                Success: true,
                Message: created == 0 ? "No directories needed creation." : $"Created {created} missing working director{(created == 1 ? "y" : "ies")}.",
                CreatedDirectories: created);
        }
        catch (Exception ex)
        {
            return new DoctorAutoFixResult(false, ex.Message, CreatedDirectories: created);
        }
    }

    public DoctorAutoFixResult ApplyLegacyMigration(string projectRoot)
    {
        var configPath = ConfigLoader.FindConfigPath(projectRoot);
        if (string.IsNullOrWhiteSpace(configPath))
            return new DoctorAutoFixResult(false, "Could not find devtool.json for migration.");

        var migration = ConfigLoader.ApplyLegacyTargetMigration(configPath, createBackup: true);
        return new DoctorAutoFixResult(
            Success: migration.Success,
            Message: migration.Message,
            BackupPath: migration.BackupPath);
    }
}
