package wails

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"golang.org/x/mod/modfile"
)

// Project is the subset of wails.json we care about.
type Project struct {
	Name string `json:"name"`
}

// ReadProject parses wails.json from dir.
func ReadProject(dir string) (*Project, error) {
	path := filepath.Join(dir, "wails.json")
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read %s: %w", path, err)
	}
	var p Project
	if err := json.Unmarshal(b, &p); err != nil {
		return nil, fmt.Errorf("parse %s: %w", path, err)
	}
	if p.Name == "" {
		return nil, fmt.Errorf("%s: name field is empty", path)
	}
	return &p, nil
}

// ProjectWailsVersion returns the require'd Wails version from go.mod.
func ProjectWailsVersion(dir string) (string, error) {
	path := filepath.Join(dir, "go.mod")
	b, err := os.ReadFile(path)
	if err != nil {
		return "", fmt.Errorf("read %s: %w", path, err)
	}
	mf, err := modfile.Parse(path, b, nil)
	if err != nil {
		return "", fmt.Errorf("parse %s: %w", path, err)
	}
	for _, r := range mf.Require {
		if r.Mod.Path == "github.com/wailsapp/wails/v2" {
			return r.Mod.Version, nil
		}
	}
	return "", fmt.Errorf("%s: no require for github.com/wailsapp/wails/v2", path)
}
