// Copyright 2022 The envd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package envd

import (
	"bytes"
	"embed"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

//go:embed api/**/*.py
var api embed.FS

const autoGeneratedHeader = `### AUTO-GENERATED ###
# To make changes, modify the following file in the envd repository:
#   envd/%s
`

func ApiStubs() fs.FS {
	f, err := fs.Sub(api, "api")
	if err != nil {
		panic(err)
	}
	return f
}

func WalkApiStubs(fn fs.WalkDirFunc) error {
	return fs.WalkDir(api, "api", fn)
}

func DumpApiStubs(dir string, callback func(string, error)) error {
	return WalkApiStubs(func(path string, d fs.DirEntry, e error) error {
		if e != nil {
			return e
		}
		var err error
		dest := filepath.Join(dir, path)
		if d.IsDir() {
			err = os.MkdirAll(dest, 0755)
		} else {
			buf := bytes.NewBufferString(fmt.Sprintf(autoGeneratedHeader, path))
			var bytes []byte
			bytes, err = api.ReadFile(path)
			if err != nil {
				return err
			}
			buf.Write(bytes)
			err = os.WriteFile(dest, buf.Bytes(), 0644)
		}
		callback(path, err)
		return err
	})
}
