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

open System
open System.IO
open System.Threading.Tasks

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

open Gdmt.StableRequest.Private

let CommandName = "gdmt-stablereq"
let CommandDescription = "file stabilization requests on Gentoo Bugzilla"

let MaintainerArgument =
    new Argument<string>("maintainer", "target maintainer e-mail to query package.gentoo.org")

let RepositoryOption =
    new Option<string>([| "-r"; "--repo" |], "ebuild repository to use, if given location changes to it")

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

        let maintainer = options.GetValueForArgument(MaintainerArgument)
        let repository = options.GetValueForOption(RepositoryOption)

        match repository with
        | empty when String.IsNullOrEmpty empty -> ()
        | repo when Directory.Exists(repo) ->
            LogMessage Success $"Using ebuild repository {repo}"
            Environment.CurrentDirectory <- repo
        | repo ->
            LogMessage Error $"Ebuild repository does not exist, given {repo}"
            $"no such directory {repo}" |> Exception |> raise

        let! stabilizationArray = GetStabilizationArray maintainer

        for stabilizationItem in stabilizationArray do
            ProcessStabilizationItem stabilizationItem

        ()
    }

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

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

    rootCommand.AddArgument MaintainerArgument

    rootCommand.AddOption RepositoryOption

    rootCommand.SetHandler CommandHandler

    rootCommand.Invoke(argv)
