package main

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

func whichdo(tgt *Tgt) (dos []string, err error) {
	var fdTmp *os.File
	fdTmp, err = os.CreateTemp("", "whichdo")
	if err != nil {
		return
	}
	err = os.Remove(fdTmp.Name())
	if err != nil {
		return
	}
	err = depBuildWrite(fdTmp, BuildUUID)
	if err != nil {
		return
	}
	var doFile string
	var upLevels int
	tgtH, tgtT := path.Split(tgt.a)
	doFile, upLevels, err = findDo(fdTmp, fdTmp.Name(), tgtH, tgtT)
	if err != nil {
		return
	}
	_, err = fdTmp.Seek(0, io.SeekStart)
	if err != nil {
		return
	}
	var data []byte
	data, err = io.ReadAll(fdTmp)
	if err != nil {
		return
	}
	{
		var dep *Dep
		dep, err = depParse(tgt, data)
		if err != nil {
			return
		}
		for _, ifcreate := range dep.ifcreates {
			dos = append(dos, ifcreate.RelTo(Cwd))
		}
		for _, ifchange := range dep.ifchanges {
			dos = append(dos, ifchange.tgt.RelTo(Cwd))
		}
	}
	if doFile == "" {
		err = fs.ErrNotExist
		return
	}
	p := make([]string, 0, upLevels+2)
	p = append(p, tgtH)
	for i := 0; i < upLevels; i++ {
		p = append(p, "..")
	}
	p = append(p, doFile)
	dos = append(dos, mustRel(Cwd, path.Join(p...)))
	return
}
