package topdata

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

func importLegacyBaseDialog(referenceBuilderDir, sourceDir string) (int, error) {
	legacyPath := filepath.Join(referenceBuilderDir, "tlk", "base.json")
	if _, err := os.Stat(legacyPath); err != nil {
		if os.IsNotExist(err) {
			return 0, nil
		}
		return 0, err
	}

	targetPath := filepath.Join(sourceDir, "base_dialog.json")
	if fileExists(targetPath) {
		current, err := loadJSONObject(targetPath)
		if err == nil {
			if entries, ok := current["entries"].(map[string]any); ok && len(entries) > 0 {
				return 0, nil
			}
		}
	}

	obj, err := loadJSONObject(legacyPath)
	if err != nil {
		return 0, err
	}
	raw, err := json.MarshalIndent(obj, "", "  ")
	if err != nil {
		return 0, err
	}
	raw = append(raw, '\n')
	if err := os.WriteFile(targetPath, raw, 0o644); err != nil {
		return 0, err
	}
	return 1, nil
}
