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

namespace Gdmt.Shared

module Ebuild =
    open System
    open System.IO

    open SimpleLog.SimpleLog

    let LayoutConfLocation = "metadata/layout.conf"

    let DoesHaveLayoutConf (path: string) : bool =
        let layoutPath = Path.Combine(path, LayoutConfLocation)

        File.Exists layoutPath

    /// <summary>Check if path is a part of a ebuild repository</summary>
    /// <param name="path">path to start checking from</param>
    /// <returns>whether given path is a part of a ebuild repository</returns>
    let IsEbuildRepository (path: string) : bool =
        path |> DoesHaveLayoutConf
        || Path.Join(path, "..") |> DoesHaveLayoutConf
        || Path.Join(path, "..", "..") |> DoesHaveLayoutConf

    /// <summary>Check if path is a part of a ebuild repository,
    /// throw a error if it is not</summary>
    /// <param name="path">path to start checking from</param>
    /// <returns></returns>
    let CheckEbuildRepository (path: string) : unit =
        let fullPath = Path.GetFullPath path

        if not (IsEbuildRepository fullPath) then
            $"provided path is not a part of any ebuild repository, given {fullPath}"
            |> Exception
            |> raise

    let GetFullPackageName (path: string) : string =
        let fullPath = path |> Path.GetFullPath
        let repoPath = Path.Join(fullPath, "..", "..")

        match (DoesHaveLayoutConf repoPath) with
        | true -> ()
        | false ->
            LogMessage Error "layout.conf file could not be found"
            LogMessage Error $"Required layout.conf from this location: {repoPath}"
            LogMessage Error "Probably wrong package path given"

            $"file not found: {repoPath}" |> Exception |> raise

        let segments = fullPath.Split('/') |> Array.rev |> Array.toList

        match segments with
        | segment1 :: segment2 :: _ -> Path.Combine(segment2, segment1)
        | _ -> "wrong list length" |> Exception |> raise

    let SpdxToEbuildLicense (licenseExpression: string) : string =
        match Map.tryFind licenseExpression LicenseMapping.SpdxToEbuildMap with
        | Some license -> license
        | None -> licenseExpression
