// goredo -- djb's redo implementation on pure Go
// Copyright (C) 2020-2026 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"io"
	"io/fs"
	"os"
	"path"
	"strings"
)

func targetsCollect(root string, tgts map[string]struct{}) error {
	dir, err := os.Open(root)
	if err != nil {
		return ErrLine(err)
	}
	defer dir.Close()
	for {
		entries, err := dir.ReadDir(1 << 10)
		if err != nil {
			if err == io.EOF {
				break
			}
			return ErrLine(err)
		}
		for _, entry := range entries {
			if !entry.IsDir() {
				continue
			}
			pth := path.Join(root, entry.Name())
			if entry.Name() == RedoDir {
				var redoDir *os.File
				redoDir, err = os.Open(pth)
				if err != nil {
					return ErrLine(err)
				}
				var redoEntries []fs.DirEntry
				redoEntries, err = redoDir.ReadDir(0)
				redoDir.Close()
				if err != nil {
					return ErrLine(err)
				}
				for _, redoEntry := range redoEntries {
					name := redoEntry.Name()
					if strings.HasSuffix(name, DepSuffix) {
						name = cwdMustRel(root, name)
						tgts[name[:len(name)-len(DepSuffix)]] = struct{}{}
					}
				}
			} else {
				if err = targetsCollect(pth, tgts); err != nil {
					return err
				}
			}
		}
	}
	return nil
}

func targetsWalker(tgts []string) ([]string, error) {
	tgtsMap := make(map[string]struct{})
	for _, tgt := range tgts {
		if err := targetsCollect(mustAbs(tgt), tgtsMap); err != nil {
			return nil, err
		}
	}
	tgts = make([]string, 0, len(tgtsMap))
	for tgt := range tgtsMap {
		tgts = append(tgts, tgt)
	}
	return tgts, nil
}

func collectWholeDeps(
	tgts map[string]*Tgt,
	deps map[string]map[string]*Tgt,
	seen map[string]*Tgt,
) {
	for _, tgt := range tgts {
		if _, exists := seen[tgt.rel]; exists {
			continue
		}
		seen[tgt.rel] = tgt
		collectWholeDeps(deps[tgt.rel], deps, seen)
	}
}
