#!/usr/bin/env -S dotnet fsi

// Copyright 2023-2024 Gentoo Authors
// Distributed under the terms of the GNU General Public License v2

#r "nuget: Fabulous.AST, 0.7.0"
#r "nuget: Org.Xgqt.SimpleLog, 0.0.0"

open System.IO

open Fabulous.AST
open Fantomas.Core
open SimpleLog.SimpleLog

open type Fabulous.AST.Ast

let SourceRoot = Path.Combine(__SOURCE_DIRECTORY__, "../../..") |> Path.GetFullPath
let LauncherSubproject = Path.Combine(SourceRoot, "gdmt/src/Gdmt.Launcher")
let SubcommandsSourceFile = Path.Combine(LauncherSubproject, "Subcommands.fs")

let SubcommandProjects =
    Directory.GetDirectories(SourceRoot, "gdmt-*")
    |> Array.filter (fun dir ->
        match dir with
        | "gdmt-shared" -> false
        | _ -> true)
    |> Array.sort

let GdmtSubcommands =
    SubcommandProjects
    |> Array.map (fun s -> s.Replace("gdmt-", ""))
    |> Array.map Path.GetFileName

let SourceAst =
    Namespace("Gdmt.Launcher") {
        NestedModule("Subcommands") {
            Value(
                "GdmtSubcommands",
                ArrayExpr() {
                    for gdmtSubcommand in GdmtSubcommands do
                        ConstantExpr($"\"{gdmtSubcommand}\"")
                }
            )
        }
    }

let Oak: NamespaceNode = Tree.compile SourceAst
let Res: string = CodeFormatter.FormatOakAsync(Oak) |> Async.RunSynchronously

LogMessage Debug "Dumping generated source code"
printfn "%s" Res

LogMessage Debug $"Writing source code to file {SubcommandsSourceFile}"
File.WriteAllText(SubcommandsSourceFile, Res)
LogMessage Success $"Successfully written to file {SubcommandsSourceFile}"

LogMessage Success "Code generation completed successfully"
