//go:build ignore

// Generate full-package aliases so full and lean resources have identical types.
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
)

func main() {
	root := os.Args[1]
	fset := token.NewFileSet()
	files, err := filepath.Glob(filepath.Join(root, "*.go"))
	if err != nil {
		panic(err)
	}
	var lines []string
	imports := map[string]string{}
	for _, path := range files {
		if strings.HasSuffix(path, "_test.go") || filepath.Base(path) == "setup.go" {
			continue
		}
		file, err := parser.ParseFile(fset, path, nil, 0)
		if err != nil {
			panic(err)
		}
		fileImports := map[string]string{}
		for _, spec := range file.Imports {
			path, _ := strconv.Unquote(spec.Path.Value)
			name := filepath.Base(path)
			if spec.Name != nil {
				name = spec.Name.Name
			}
			fileImports[name] = path
		}
		for _, decl := range file.Decls {
			switch d := decl.(type) {
			case *ast.GenDecl:
				for _, spec := range d.Specs {
					switch s := spec.(type) {
					case *ast.TypeSpec:
						if s.Name.IsExported() {
							lines = append(lines, "type "+s.Name.Name+" = core."+s.Name.Name)
						}
					case *ast.ValueSpec:
						for _, name := range s.Names {
							if name.IsExported() {
								lines = append(lines, d.Tok.String()+" "+name.Name+" = core."+name.Name)
							}
						}
					}
				}
			case *ast.FuncDecl:
				if d.Recv != nil || !d.Name.IsExported() {
					continue
				}
				// Forward functions as declarations, not mutable exported variables.
				ast.Inspect(d.Type, func(node ast.Node) bool {
					if selector, ok := node.(*ast.SelectorExpr); ok {
						if qualifier, ok := selector.X.(*ast.Ident); ok {
							if path, ok := fileImports[qualifier.Name]; ok {
								imports[qualifier.Name] = path
							}
						}
					}
					return true
				})
				var signature bytes.Buffer
				printer.Fprint(&signature, fset, d.Type)
				var args []string
				for _, field := range d.Type.Params.List {
					for _, name := range field.Names {
						arg := name.Name
						if _, ok := field.Type.(*ast.Ellipsis); ok {
							arg += "..."
						}
						args = append(args, arg)
					}
				}
				prefix := ""
				if d.Type.Results != nil && len(d.Type.Results.List) > 0 {
					prefix = "return "
				}
				lines = append(lines, "func "+d.Name.Name+strings.TrimPrefix(signature.String(), "func")+" { "+prefix+"core."+d.Name.Name+"("+strings.Join(args, ",")+") }")
			}
		}
	}
	sort.Strings(lines)
	fmt.Println("// Code generated by scripts/export-aliases.go; DO NOT EDIT.\npackage microsandbox\nimport (core \"github.com/superradcompany/microsandbox/sdk/go/core\"")
	var names []string
	for name := range imports {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		fmt.Printf("%s %q\n", name, imports[name])
	}
	fmt.Println(")")
	for _, line := range lines {
		fmt.Println(line)
	}
}
