package topdata

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

func importLegacyWingmodel(referenceBuilderDir, dataDir string, legacyTLK *legacyTLKData) (int, error) {
	_ = legacyTLK

	legacyDir := filepath.Join(referenceBuilderDir, "data", "wingmodel")
	if _, err := os.Stat(legacyDir); err != nil {
		if os.IsNotExist(err) {
			return 0, nil
		}
		return 0, err
	}

	targetDir := filepath.Join(dataDir, "wingmodel")
	targetBasePath := filepath.Join(targetDir, "base.json")
	targetLockPath := filepath.Join(targetDir, "lock.json")
	targetModulesDir := filepath.Join(targetDir, "modules")
	targetModulePaths := []string{
		filepath.Join(targetModulesDir, "add.json"),
		filepath.Join(targetModulesDir, "ovr_wingprefixes.json"),
	}
	if fileExists(targetBasePath) && fileExists(targetLockPath) {
		allModulesPresent := true
		for _, path := range targetModulePaths {
			if !fileExists(path) {
				allModulesPresent = false
				break
			}
		}
		if allModulesPresent {
			return 0, nil
		}
	}

	baseObj, err := loadJSONObject(filepath.Join(legacyDir, "base.json"))
	if err != nil {
		return 0, err
	}
	baseObj["output"] = "wingmodel.2da"

	lockObj, err := loadJSONObject(filepath.Join(legacyDir, "lock.json"))
	if err != nil {
		return 0, err
	}

	moduleNames := []string{"add.json", "ovr_wingprefixes.json"}
	moduleObjs := make([]map[string]any, 0, len(moduleNames))
	for _, name := range moduleNames {
		obj, err := loadJSONObject(filepath.Join(legacyDir, "modules", name))
		if err != nil {
			return 0, err
		}
		moduleObjs = append(moduleObjs, obj)
	}

	if err := os.MkdirAll(targetModulesDir, 0o755); err != nil {
		return 0, err
	}

	writes := []struct {
		path string
		obj  map[string]any
	}{
		{path: targetBasePath, obj: baseObj},
		{path: targetLockPath, obj: lockObj},
		{path: targetModulePaths[0], obj: moduleObjs[0]},
		{path: targetModulePaths[1], obj: moduleObjs[1]},
	}
	for _, write := range writes {
		raw, err := json.MarshalIndent(write.obj, "", "  ")
		if err != nil {
			return 0, err
		}
		raw = append(raw, '\n')
		if err := os.WriteFile(write.path, raw, 0o644); err != nil {
			return 0, err
		}
	}
	return len(writes), nil
}
