package main

import (
	"errors"

	"go.wit.com/lib/protobuf/gitpb"
	"go.wit.com/log"
)

// this will make go.mod and go.sum files, but you have to
// have the files in .gitignore for now
func doSmart(repo *gitpb.Repo) error {
	if !repo.IsValid() {
		log.Info(repo.GoPath, "is invalid. fix your repos.pb file with 'forge' first")
		log.Info("")
		log.Info("go install go.wit.com/apps/forge@latest")
		log.Info("")
		return errors.New(repo.GoPath + " is invalid. fix your repository list with 'forge' first")
	}
	log.Info(repo.GoPath, "is valid according to forge")

	// if the repo has go.mod in the repo...
	if err := repo.RepoIgnoresGoMod(); err != nil {
		log.Info("never modify go.mod or go.sum for this repo", repo.GoPath)
		log.Info("We recommend you add 'go.*' to your .gitignore file and store those files as git tag metadata")
		repo.ParseGoSum()
		return nil
	}

	// erase the go.mod and go.sum files
	eraseGoMod(repo)

	// try to restore from the git metadata
	cname := repo.GetCurrentBranchName()
	if err := repo.AutogenRestore(cname); err == nil {
		log.Info(repo.GoPath, "files were restored ok from git metadata (notes)")
		configSave = true
		return nil
	}

	// attempt to restore from ~/go/pkg/mod/
	if err := restoreFromGoPkg(repo); err == nil {
		configSave = true
		return nil
	}

	// actually will re-create go.sum and go.mod now
	if err := redoGoMod(repo); err != nil {
		return err
	}

	// the first time, it'll attempt to fix some stuff
	cleanGoDepsCheckOk(repo)
	// try to trim junk
	if err := trimGoSum(repo); err != nil {
		return err
	}
	repo.ParseGoSum()

	// everything worked more or less
	configSave = true
	return nil
}