using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace DansoriEQ.App.Apo;

public static class ApoConfigInstaller
{
    private const string IncludeLine = "Include: ai_eq.txt";

    public static bool IsIncluded(string configDir)
    {
        var path = Path.Combine(configDir, "config.txt");
        if (!File.Exists(path)) return false;
        return File.ReadAllLines(path)
                   .Any(l => l.Trim().Equals(IncludeLine, StringComparison.OrdinalIgnoreCase));
    }

    /// <summary>Tries direct write first; falls back to an elevated PowerShell call.</summary>
    public static bool TryAddInclude(string configDir)
    {
        if (IsIncluded(configDir)) return true;

        var configTxt = Path.Combine(configDir, "config.txt");
        try
        {
            File.AppendAllText(configTxt, Environment.NewLine + IncludeLine + Environment.NewLine);
            return true;
        }
        catch (UnauthorizedAccessException)
        {
            return TryAddIncludeElevated(configTxt);
        }
        catch
        {
            return false;
        }
    }

    /// <summary>Ensure an empty ai_eq.txt exists so APO doesn't log a missing-file warning.</summary>
    public static void EnsureAiEqFile(string configDir)
    {
        var target = Path.Combine(configDir, "ai_eq.txt");
        if (!File.Exists(target))
            File.WriteAllText(target, "# Dansori EQ — managed automatically\n");
    }

    private static bool TryAddIncludeElevated(string configTxtPath)
    {
        // Escape single-quotes in path for PowerShell
        var escaped = configTxtPath.Replace("'", "''");
        var psCmd = $"Add-Content -Encoding UTF8 -Path '{escaped}' -Value \"`r`nInclude: ai_eq.txt`r`n\"";
        try
        {
            var psi = new ProcessStartInfo("powershell.exe",
                $"-NonInteractive -WindowStyle Hidden -Command \"{psCmd}\"")
            {
                Verb = "runas",
                UseShellExecute = true,
                WindowStyle = ProcessWindowStyle.Hidden
            };
            using var proc = Process.Start(psi)
                ?? throw new InvalidOperationException("Process.Start returned null");
            proc.WaitForExit(15_000);
            return IsIncluded(Path.GetDirectoryName(configTxtPath)!);
        }
        catch
        {
            return false;
        }
    }
}
