using Faithlife.Build;
using NuGet.Configuration;
using NuGet.Versioning;
using static Faithlife.Build.DotNetRunner;

internal static class Build
{
	public static int Main(string[] args) => BuildRunner.Execute(args, build =>
	{
		var artifactDirOption = build.AddOption("--artifact-dir <directory>", "Artifact directory", defaultValue: "artifacts");

		var dotNetSettings = new DotNetBuildSettings();

		build.AddDotNetTargets(dotNetSettings);

		build.Target("deployment-package")
			.DependsOn("test")
			.Describe("Creates the deployment package")
			.Does(() =>
			{
				var projectPath = Path.Combine("src", "Twain.Web", "Twain.Web.csproj");

				if (artifactDirOption.Value != null)
					DeleteDirectory(artifactDirOption.Value);

				RunDotNet(new[]
					{
						"publish", projectPath,
						"-c", dotNetSettings.GetConfiguration(),
						"-o", artifactDirOption.Value,
						dotNetSettings.GetPlatformArg(),
						"--no-build",
						dotNetSettings.GetVerbosityArg(),
						dotNetSettings.GetMaxCpuCountArg()
					});
			});

		build.Target("codegen")
			.DependsOn("restore")
			.Describe("Generates code from the FSD")
			.Does(() => CodeGen(verify: false));

		build.Target("verify-codegen")
			.DependsOn("restore")
			.Describe("Ensures that the generated code is up-to-date")
			.Does(() => CodeGen(verify: true));

		build.Target("build")
			.DependsOn("verify-codegen");

		void CodeGen(bool verify)
		{
			const string slash = "/";
			const string fsdFilePath = "fsd/OapApi.v1.fsd";
			const string clientProject = "OapApi.v1.Client";
			const string webApiProject = "OapApi.v1";

			var csharpCodeGenerator = DotNetLocalTool.Create("fsdgencsharp");
			var aspnetCodeGenerator = DotNetLocalTool.Create("fsdgenaspnet");
			var mdCodeGenerator = DotNetLocalTool.Create("fsdgenmd");
			var swaggerCodeGenerator = DotNetLocalTool.Create("fsdgenswagger");

			var verifyOption = verify ? "--verify" : null;

			csharpCodeGenerator.Run(fsdFilePath, Path.Combine("src", clientProject) + slash, "--namespace", clientProject, "--clean", "--newline", "lf", verifyOption);
			aspnetCodeGenerator.Run(fsdFilePath, Path.Combine("src", "Modules", webApiProject, "Controllers"), "--namespace", $"{webApiProject}.Controllers", "--newline", "lf", verifyOption, "--target", "core");
			mdCodeGenerator.Run(fsdFilePath, Path.Combine("docs", "api") + slash, "--clean", "--newline", "lf", verifyOption);
			swaggerCodeGenerator.Run(fsdFilePath, Path.Combine("src", "Modules", webApiProject, "swagger.json"), "--json", "--newline", "lf", verifyOption);
		}
	});
}
