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

open System
open System.Threading.Tasks

open SimpleLog.SimpleLog
open System.CommandLine
open System.CommandLine.Invocation

open Gdmt.Shared.Ebuild

open Gdmt.License.Private

let CommandName = "gdmt-license"
let CommandDescription = "list project licenses in Gentoo style"

let ProjectArgument =
    new Argument<string>("project", "solution or project path to use")

ProjectArgument.SetDefaultValue "."

let CommandHandler (context: InvocationContext) : Task =
    task {
        let options = context.ParseResult

        let projectFile = options.GetValueForArgument ProjectArgument

        let nugetLicenseOutput = ExecuteNugetLicense projectFile
        let nugets = NugetLicenseProvider.Parse nugetLicenseOutput

        nugets
        |> Array.map (fun nuget -> (nuget.License, nuget.PackageId))
        |> Array.sort
        // Place nulls at the end.
        |> Array.rev
        |> Array.map (fun nuget ->
            let (license, name) = nuget

            match license with
            | empty when String.IsNullOrEmpty empty -> LogMessage Error $"{name} license was not detected"
            | _ -> LogMessage Debug $"{name} has license: {license}"

            license)
        |> Array.filter IsAcceptedLicense
        |> Array.sort
        |> Array.distinct
        |> Array.map SpdxToEbuildLicense
        |> String.concat " "
        |> (fun s -> printfn "Following licenses of dependencies were found: %s" s)

        ()
    }

[<EntryPoint>]
let main argv =
    let rootCommand = RootCommand(CommandName)

    rootCommand.Name <- CommandName
    rootCommand.Description <- CommandDescription

    rootCommand.AddArgument ProjectArgument

    rootCommand.SetHandler CommandHandler

    rootCommand.Invoke(argv)
