using System.Text.Json;

namespace CodeRemoteManager.SetupApp;

internal static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        if (args is ["--migrate-config"])
        {
            Environment.ExitCode = RunConfigurationMigrationAsync().GetAwaiter().GetResult();
            return;
        }

        ApplicationConfiguration.Initialize();
        Application.Run(new MainForm());
    }

    private static async Task<int> RunConfigurationMigrationAsync()
    {
        try
        {
            var configPath = Environment.GetEnvironmentVariable("CODE_REMOTE_MANAGER_CONFIG_PATH");
            if (string.IsNullOrWhiteSpace(configPath)) return 1;
            var request = JsonSerializer.Deserialize<HeadlessConfigurationRequest>(
                await Console.In.ReadToEndAsync(),
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            if (request is null) return 1;

            var existingJson = File.Exists(configPath)
                ? await File.ReadAllTextAsync(configPath)
                : null;
            var candidate = ConfigurationMigration.BuildCandidate(
                existingJson,
                new SetupConfigurationInput(request.CodexCliPath, request.TailnetOrigin, request.ProjectPath),
                new SetupConfigurationDefaults(request.DataDir, request.DesktopCodexHome));
            var validator = new BackendConfigurationValidator(
                Path.Combine(AppContext.BaseDirectory, "node.exe"),
                Path.Combine(AppContext.BaseDirectory, "app", "backend", "src", "config-validator-cli.js"));
            var store = new ConfigurationStore(validator.ValidateAsync);
            await store.SaveAsync(configPath, candidate);
            return 0;
        }
        catch
        {
            return 1;
        }
    }
}

internal sealed record HeadlessConfigurationRequest(
    string CodexCliPath,
    string TailnetOrigin,
    string? ProjectPath,
    string DataDir,
    string DesktopCodexHome);
