package topdata

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

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

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

	targetDir := filepath.Join(dataDir, "skills")
	targetBasePath := filepath.Join(targetDir, "base.json")
	targetLockPath := filepath.Join(targetDir, "lock.json")
	targetModulesDir := filepath.Join(targetDir, "modules")
	moduleNames := []string{
		"add_athletics.json",
		"add_disguise.json",
		"add_linguistics.json",
		"add_perception.json",
		"add_scriptcraft.json",
		"add_sensemotive.json",
		"add_stealth.json",
		"add_survival.json",
		"add_userope.json",
		filepath.Join("craft", "add_craftalchemy.json"),
		filepath.Join("craft", "add_craftcooking.json"),
		filepath.Join("craft", "add_craftjewelry.json"),
		filepath.Join("craft", "add_craftleatherworking.json"),
		filepath.Join("craft", "add_craftstonework.json"),
		filepath.Join("craft", "add_crafttextiles.json"),
		filepath.Join("craft", "ovr_craftarmorsmithing.json"),
		filepath.Join("craft", "ovr_crafttinkering.json"),
		filepath.Join("craft", "ovr_craftweaponsmithing.json"),
		filepath.Join("craft", "ovr_craftwoodworking.json"),
		filepath.Join("knowledge", "add_knowledgearcana.json"),
		filepath.Join("knowledge", "add_knowledgearchitecture.json"),
		filepath.Join("knowledge", "add_knowledgedungeoneering.json"),
		filepath.Join("knowledge", "add_knowledgegeography.json"),
		filepath.Join("knowledge", "add_knowledgehistory.json"),
		filepath.Join("knowledge", "add_knowledgelocal.json"),
		filepath.Join("knowledge", "add_knowledgenature.json"),
		filepath.Join("knowledge", "add_knowledgenobility.json"),
		filepath.Join("knowledge", "add_knowledgeplanar.json"),
		filepath.Join("knowledge", "add_knowledgereligion.json"),
		"ovr_acrobatics.json",
		"ovr_animalhandling.json",
		"ovr_appraise.json",
		"ovr_concentration.json",
		"ovr_disabledevice.json",
		"ovr_heal.json",
		"ovr_hiddenskills.json",
		"ovr_influence.json",
		"ovr_openlock.json",
		"ovr_parry.json",
		"ovr_searchtowis.json",
		"ovr_sleightofhand.json",
		"ovr_taunttointimidate.json",
		"rmv_removedskills.json",
	}
	targetModulePaths := make([]string, 0, len(moduleNames))
	for _, name := range moduleNames {
		targetModulePaths = append(targetModulePaths, filepath.Join(targetModulesDir, name))
	}
	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"] = "skills.2da"
	canonicalizeWikiMetadataDocument(baseObj)

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

	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
		}
		canonicalizeWikiMetadataDocument(obj)
		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},
	}
	for i, path := range targetModulePaths {
		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
			return 0, err
		}
		writes = append(writes, struct {
			path string
			obj  map[string]any
		}{path: path, obj: moduleObjs[i]})
	}

	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
}
