package main

import (
	"errors"
	"fmt"
	"go/ast"
	"go/token"
	"go/types"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/tools/go/packages"
)

type PackageInfo struct {
	Package *types.Package
	Files   []*ast.File
	Fset    *token.FileSet
}

func LoadPackage(dir string) (*PackageInfo, error) {
	pattern := "."
	if dir != "" {
		pattern = dir
	}
	return loadPackageWithPattern(pattern, dir)
}

func LoadPackageFromImport(importPath, baseDir string) (*PackageInfo, error) {
	pattern := importPath
	if strings.HasPrefix(importPath, ".") || filepath.IsAbs(importPath) {
		pattern = importPath
	}
	return loadPackageWithPattern(pattern, baseDir)
}

func loadPackageWithPattern(pattern, dir string) (*PackageInfo, error) {
	cfg := &packages.Config{
		Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo,
		Dir:  dir,
		Env:  append(os.Environ(), "GO111MODULE=on"),
	}

	pkgs, err := packages.Load(cfg, pattern)
	if err != nil {
		return nil, err
	}
	if len(pkgs) == 0 {
		return nil, fmt.Errorf("no Go packages found for %s", pattern)
	}

	pkg := pkgs[0]
	if pkg.Types == nil {
		return nil, fmt.Errorf("failed to load types for %s: %w", pattern, packagesError(pkgs))
	}

	return &PackageInfo{
		Package: pkg.Types,
		Files:   pkg.Syntax,
		Fset:    pkg.Fset,
	}, nil
}

func packagesError(pkgs []*packages.Package) error {
	for _, pkg := range pkgs {
		if len(pkg.Errors) == 0 {
			continue
		}
		msgs := make([]string, 0, len(pkg.Errors))
		for _, err := range pkg.Errors {
			msgs = append(msgs, err.Error())
		}
		return errors.New(strings.Join(msgs, "\n"))
	}
	return nil
}

func FindInterface(pkgInfo *PackageInfo, name string) (*types.Interface, error) {
	obj := pkgInfo.Package.Scope().Lookup(name)
	if obj == nil {
		return nil, fmt.Errorf("interface %s not found", name)
	}
	typeName, ok := obj.(*types.TypeName)
	if !ok {
		return nil, fmt.Errorf("%s is not a type", name)
	}
	iface, ok := typeName.Type().Underlying().(*types.Interface)
	if !ok {
		return nil, fmt.Errorf("%s is not an interface", name)
	}
	iface.Complete()
	return iface, nil
}
