package u

import (
	"errors"
	"log/slog"
	"os"
	"strings"
)

func FileExist(filename string) bool {
	if _, err := os.Stat(filename); err == nil {
		return true

	} else if errors.Is(err, os.ErrNotExist) {
		return false
	} else {
		slog.Warn("Schrödinger's file: it may or may not exist", "file", filename) 
		// Schrodinger: file may or may not exist. To be extra safe it will
		// report the file doest not exist
		return false
	}
}

// This is just a slin wraper to make easier to compose path in the template
type Pathing struct {
	sb strings.Builder
}

func NewPathing() *Pathing {
	return &Pathing{}
}

func (s *Pathing) AddPath(p string) *Pathing {
	if len(p) == 0 {
		return s
	}

	// if it has trailing / remove it
	if p[len(p)-1] == '/' {
		p = p[:len(p)-1]
		return s.AddPath(p)
	}

	// if it does not have it so add
	if p[0] == '/' {
		s.sb.WriteString(p)
	} else {
		s.sb.WriteString("/" + p)
	}

	return s
}

func (s *Pathing) AddPaths(p []string) *Pathing {
	for _, v := range p {
		s.AddPath(v)
	}

	return s
}

func (s *Pathing) Done() string {
	return s.sb.String()
}