using System.IO;

namespace ClaudeDo.Installer.Core;

public static class AutostartShortcut
{
    public const string FileName = "ClaudeDo Worker.lnk";

    public static string DefaultStartupDir =>
        Environment.GetFolderPath(Environment.SpecialFolder.Startup);

    public static string PathIn(string startupDir) => Path.Combine(startupDir, FileName);

    /// <summary>Creates or updates the Startup shortcut. Returns false if it already pointed at <paramref name="workerExe"/> and was left untouched.</summary>
    public static bool Install(string startupDir, string workerExe)
    {
        Directory.CreateDirectory(startupDir);
        var shortcutPath = PathIn(startupDir);
        if (File.Exists(shortcutPath))
        {
            var existingTarget = ShortcutFactory.TryGetTarget(shortcutPath);
            if (existingTarget is not null && PathsEqual(existingTarget, workerExe))
                return false;
        }

        var workingDir = Path.GetDirectoryName(workerExe) ?? startupDir;
        ShortcutFactory.CreateShortcut(shortcutPath, workerExe, workingDir, "ClaudeDo background worker");
        return true;
    }

    private static bool PathsEqual(string a, string b) =>
        string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);

    public static void Remove(string startupDir)
    {
        var path = PathIn(startupDir);
        if (File.Exists(path)) File.Delete(path);
    }
}
