using System.Diagnostics;

var deployDir = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", ".."));
var webDir = Path.GetFullPath(Path.Combine(deployDir, "..", "Web"));
var webProject = Path.Combine(webDir, "Web.csproj");
var publishDir = Path.Combine(Path.GetTempPath(), "gsr-deploy", Guid.NewGuid().ToString());
var deploymentToken = Environment.GetEnvironmentVariable("GSR_DeployToken") ?? throw new InvalidOperationException("GSR_DeployToken environment variable not set.");
var deployEnv = Environment.GetEnvironmentVariable("GSR_DeployEnv") ?? "preview";

// 1. Publish
Console.WriteLine("Publishing Web project...");
Run("dotnet", $"publish \"{webProject}\" -c Release -o \"{publishDir}\"");

var wwwroot = Path.Combine(publishDir, "wwwroot");
if (!Directory.Exists(wwwroot))
{
    Console.Error.WriteLine("wwwroot not found in publish output.");
    return 1;
}

// 2. Deploy
Console.WriteLine("Deploying to Azure Static Web Apps...");
Run("swa.cmd", $"deploy \"{wwwroot}\" --deployment-token \"{deploymentToken}\" --app-location \"{webDir}\" --env \"{deployEnv}\"");

Console.WriteLine("Deploy successful!");
return 0;

static void Run(string fileName, string arguments)
{
    var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!;
    process.WaitForExit();
    if (process.ExitCode != 0) { Environment.Exit(process.ExitCode); }
}