package cmd

import (
	"fmt"
	"os"
	"strings"

	"github.com/cgrindel/rules_swift_package_manager/tools/swift_deps_index/internal/swift"
	"github.com/cgrindel/rules_swift_package_manager/tools/swift_deps_index/internal/swiftpkg"
	"github.com/spf13/cobra"
)

const dependencyIndexPerms = 0644

var outputPath string

// createCmd represents the create command
var createCmd = &cobra.Command{
	Use:   "create [<pkg_info_path>...]",
	Short: "Create a Swift dependencies index file.",
	Long: `Create a Swift dependencies index JSON file from pkg_info.json
files as generated by rules_swift_package_manager.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		di := swift.NewDependencyIndex()
		for _, identityPkgInfoPathPair := range args {
			identity, pkgInfoPath, err := parseIdentityPkgInfoPathPair(identityPkgInfoPathPair)
			if err != nil {
				return err
			}
			pkgInfoJSON, err := os.ReadFile(pkgInfoPath)
			if err != nil {
				return err
			}
			pkgInfo, err := swiftpkg.NewPackageInfoFromJSON(pkgInfoJSON)
			if err != nil {
				return err
			}
			if err := indexSwiftPackage(di, identity, pkgInfo); err != nil {
				return err
			}
		}
		diJSON, err := di.JSON()
		if err != nil {
			return err
		}
		if outputPath != "" {
			if err := os.WriteFile(outputPath, diJSON, dependencyIndexPerms); err != nil {
				return err
			}
		} else {
			fmt.Println(string(diJSON))
		}
		return nil
	},
}

func init() {
	rootCmd.AddCommand(createCmd)
	createCmd.Flags().StringVarP(
		&outputPath, "output", "o", "", "The path where to write the Swift index file.")
}

func indexSwiftPackage(di *swift.DependencyIndex, identity string, pkgInfo *swiftpkg.PackageInfo) error {
	bzlRepo := swift.NewBazelRepo(identity, pkgInfo, nil)
	if err := di.IndexBazelRepo(bzlRepo); err != nil {
		return err
	}
	di.AddDirectDependency(identity)
	return nil
}

func parseIdentityPkgInfoPathPair(pair string) (string, string, error) {
	split := strings.SplitN(pair, "=", 2)
	if len(split) != 2 {
		return "", "", fmt.Errorf("invalid identity-package info path pair (%s)", pair)
	}
	identity := split[0]
	pkgInfoPath := split[1]
	return identity, pkgInfoPath, nil
}
