package topdata

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

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

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

	targetDir := filepath.Join(dataDir, "feat")
	targetBasePath := filepath.Join(targetDir, "base.json")
	var targetObj map[string]any
	if _, err := os.Stat(targetBasePath); err == nil {
		targetObj, err = loadJSONObject(targetBasePath)
		if err != nil {
			return 0, err
		}
	} else if !os.IsNotExist(err) {
		return 0, err
	}
	if targetObj != nil {
		if rows, ok := targetObj["rows"].([]any); ok && len(rows) > 0 {
			return 0, nil
		}
	}

	baseObj, err := loadJSONObject(legacyBasePath)
	if err != nil {
		return 0, err
	}
	baseObj["output"] = "feat.2da"
	baseObj["compare_reference"] = false
	canonicalizeWikiMetadataDocument(baseObj)

	if err := os.MkdirAll(targetDir, 0o755); err != nil {
		return 0, err
	}
	raw, err := json.MarshalIndent(baseObj, "", "  ")
	if err != nil {
		return 0, err
	}
	raw = append(raw, '\n')
	if err := os.WriteFile(targetBasePath, raw, 0o644); err != nil {
		return 0, err
	}
	return 1, nil
}
