using System.ServiceProcess;
using System.Diagnostics;

namespace ITNexusAgent;

public class AgentService : ServiceBase
{
    private CancellationTokenSource? _cts;
    private Task? _worker;

    public AgentService()
    {
        ServiceName = "IT Nexus Agent";
        CanStop = true;
        CanPauseAndContinue = false;
        AutoLog = false;
    }

    protected override void OnStart(string[] args)
    {
        _cts = new CancellationTokenSource();
        _worker = Task.Run(() => new AgentWorker(_cts.Token).RunAsync());
    }

    protected override void OnStop()
    {
        _cts?.Cancel();
        _worker?.Wait(TimeSpan.FromSeconds(10));
    }

    public static void Install(string exePath)
    {
        // Bestehenden Service stoppen + löschen (falls vorhanden, damit binPath aktualisiert wird)
        Run("net.exe",    "stop \"IT Nexus Agent\"");
        System.Threading.Thread.Sleep(2000);
        Run("sc.exe",     "delete \"IT Nexus Agent\"");
        System.Threading.Thread.Sleep(1000);

        // Dashboard-Prozesse beenden damit EXE nicht gesperrt ist
        foreach (var p in System.Diagnostics.Process.GetProcessesByName("IT-Nexus-Agent"))
        {
            try { if (p.MainModule?.FileName != exePath) p.Kill(); } catch { }
        }

        // Neu erstellen mit korrektem Pfad
        Run("sc.exe", $"create \"IT Nexus Agent\" binPath= \"{exePath}\" start= auto DisplayName= \"IT Nexus Agent\"");
        Run("sc.exe", "description \"IT Nexus Agent\" \"Cereda Systems IT Nexus Monitoring Agent\"");
        Run("sc.exe", "failure \"IT Nexus Agent\" reset= 60 actions= restart/5000/restart/10000/restart/30000");
        Run("net.exe", "start \"IT Nexus Agent\"");

        AgentWorker.Log($"Service installiert: {exePath}");
    }

    private static void Run(string exe, string args)
    {
        try
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(exe, args)
            { CreateNoWindow = true, UseShellExecute = false })?.WaitForExit();
        }
        catch { }
    }

    public static void Uninstall()
    {
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("net.exe",
            "stop \"IT Nexus Agent\"")
        { CreateNoWindow = true })?.WaitForExit();

        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("sc.exe",
            "delete \"IT Nexus Agent\"")
        { CreateNoWindow = true })?.WaitForExit();

        AgentWorker.Log("Service deinstalliert");
    }

    // Migration vom alten PowerShell-Agent
    public static void MigrateFromOldAgent()
    {
        try
        {
            var oldDataDir = @"C:\ProgramData\IT Nexus Agent";
            var oldConfigPath = Path.Combine(oldDataDir, "config.json");

            // Alte Scheduled Tasks entfernen
            foreach (var taskName in new[] { "IT Nexus Agent", "IT Nexus Announcement Watcher" })
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("schtasks.exe",
                    $"/delete /tn \"{taskName}\" /f")
                { CreateNoWindow = true })?.WaitForExit();
            }

            // Alte PS1-Dateien bereinigen
            if (Directory.Exists(oldDataDir))
            {
                foreach (var f in Directory.GetFiles(oldDataDir, "*.ps1"))
                    try { File.Delete(f); } catch { }
                foreach (var f in Directory.GetFiles(oldDataDir, "*.update"))
                    try { File.Delete(f); } catch { }
            }

            AgentWorker.Log("Migration vom alten PowerShell-Agent abgeschlossen");
        }
        catch (Exception ex)
        {
            AgentWorker.Log($"Migration-Warnung: {ex.Message}");
        }
    }
}
