package topdata

import (
	"os"
	"path/filepath"
	"testing"

	"gitea.westgate.pw/ShadowsOverWestgate/sow-tools/internal/project"
)

func TestValidateProjectAcceptsCanonicalTopDataLayout(t *testing.T) {
	root := t.TempDir()
	mkdirAll(t, filepath.Join(root, "src"))
	mkdirAll(t, filepath.Join(root, "assets"))
	mkdirAll(t, filepath.Join(root, "build"))
	mkdirAll(t, filepath.Join(root, "topdata", "data", "feat", "modules"))
	mkdirAll(t, filepath.Join(root, "topdata", "tlk", "modules"))
	writeFile(t, filepath.Join(root, "topdata", "base_dialog.json"), "{}\n")
	writeFile(t, filepath.Join(root, "topdata", "data", "feat", "base.json"), `{"output":"feat.2da","columns":["LABEL"],"rows":[{"id":0,"LABEL":"Feat","key":"feat:test"}]}`+"\n")
	writeFile(t, filepath.Join(root, "topdata", "data", "feat", "lock.json"), `{"feat:test":0}`+"\n")
	writeFile(t, filepath.Join(root, "topdata", "data", "feat", "modules", "entry.json"), `{"overrides":[{"id":0,"LABEL":"Feat"}]}`+"\n")
	writeFile(t, filepath.Join(root, "topdata", "tlk", "base.json"), `{"language":"en","entries":{"feat:test.name":"Feat"}}`+"\n")
	writeFile(t, filepath.Join(root, "topdata", "tlk", "lock.json"), `{"feat:test.name":0}`+"\n")
	mkdirAll(t, filepath.Join(root, "reference"))
	writeFile(t, filepath.Join(root, "reference", "build.py"), "print('ok')\n")

	p := &project.Project{
		Root: root,
		Config: project.Config{
			Module: project.ModuleConfig{Name: "Test", ResRef: "test"},
			Paths:  project.PathConfig{Source: "src", Assets: "assets", Build: "build"},
			TopData: project.TopDataConfig{
				Source:           "topdata",
				Build:            "build/topdata",
				ReferenceBuilder: "reference",
			},
		},
	}

	report := ValidateProject(p)
	if report.HasErrors() {
		t.Fatalf("expected no topdata validation errors, got %#v", report.Diagnostics)
	}
}

func TestBuildReferenceAndCompareReference(t *testing.T) {
	root := t.TempDir()
	mkdirAll(t, filepath.Join(root, "src"))
	mkdirAll(t, filepath.Join(root, "assets"))
	mkdirAll(t, filepath.Join(root, "build"))
	mkdirAll(t, filepath.Join(root, "topdata", "data"))
	mkdirAll(t, filepath.Join(root, "topdata", "tlk"))
	writeFile(t, filepath.Join(root, "topdata", "base_dialog.json"), "{}\n")
	mkdirAll(t, filepath.Join(root, "reference"))
	writeFile(t, filepath.Join(root, "reference", "build.py"), `#!/usr/bin/env python3
import os, sys
out = None
tlk = None
args = sys.argv[1:]
for i, arg in enumerate(args):
    if arg == "--out":
        out = args[i + 1]
    if arg == "--tlk-dir":
        tlk = args[i + 1]
os.makedirs(out, exist_ok=True)
os.makedirs(tlk, exist_ok=True)
with open(os.path.join(out, "feat.2da"), "w", encoding="utf-8") as f:
    f.write("2DA V2.0\n\n")
with open(os.path.join(tlk, "sow_tlk.tlk"), "wb") as f:
    f.write(b"TLK")
`)

	p := &project.Project{
		Root: root,
		Config: project.Config{
			Module: project.ModuleConfig{Name: "Test", ResRef: "test"},
			Paths:  project.PathConfig{Source: "src", Assets: "assets", Build: "build"},
			TopData: project.TopDataConfig{
				Source:           "topdata",
				Build:            "build/topdata",
				ReferenceBuilder: "reference",
			},
		},
	}

	result, err := BuildReference(p, nil)
	if err != nil {
		t.Fatalf("BuildReference failed: %v", err)
	}
	if result.Files2DA != 1 || result.FilesTLK != 1 {
		t.Fatalf("unexpected build result: %#v", result)
	}

	compare, err := CompareReference(p, nil)
	if err != nil {
		t.Fatalf("CompareReference failed: %v", err)
	}
	if compare.Compared2DA != 1 || compare.ComparedTLK != 1 {
		t.Fatalf("unexpected compare result: %#v", compare)
	}
}

func mkdirAll(t *testing.T, path string) {
	t.Helper()
	if err := os.MkdirAll(path, 0o755); err != nil {
		t.Fatalf("mkdir %s: %v", path, err)
	}
}

func writeFile(t *testing.T, path, content string) {
	t.Helper()
	if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
		t.Fatalf("write %s: %v", path, err)
	}
}
