package configrefresh_test

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

	"iop/packages/go/config"
)

func writeYAML(t *testing.T, dir, name, content string) string {
	t.Helper()
	path := filepath.Join(dir, name)
	if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
		t.Fatalf("write %s: %v", name, err)
	}
	return path
}

// buildNormalizedCurrent creates a current config that mimics what a running
// serve process holds after loadRuntimeConfig normalization. Empty logging
// paths are resolved, explicit logging paths are preserved, and bootstrap
// artifact_dir is resolved to the effective runtime path.
func buildNormalizedCurrent(t *testing.T, path string) *config.EdgeConfig {
	t.Helper()
	cfg, err := config.LoadEdge(path)
	if err != nil {
		t.Fatalf("load current: %v", err)
	}
	// Apply the same normalization that loadRuntimeConfig performs.
	// NOTE: explicit relative logging.path is preserved exactly to match
	// edgecmd.ResolveEdgeLogPath – only empty paths are resolved.
	if cfg.Logging.Path == "" {
		cfg.Logging.Path = _normalizedLogPath()
	}
	// Explicit absolute / relative paths are intentionally left untouched.
	cfg.Bootstrap.ArtifactDir = _normalizeArtifactDir(cfg.Bootstrap.ArtifactDir)
	return cfg
}

func _normalizedLogPath() string {
	if exe, err := os.Executable(); err == nil {
		return filepath.Join(filepath.Dir(exe), "logs", "edge.log")
	}
	if wd, err := os.Getwd(); err == nil {
		return filepath.Join(wd, "logs", "edge.log")
	}
	return "logs/edge.log"
}

func _normalizeArtifactDir(dir string) string {
	if dir == "" {
		dir = "artifacts"
	}
	if filepath.IsAbs(dir) {
		return dir
	}
	return filepath.Join(binaryDirForTesting(), dir)
}

func binaryDirForTesting() string {
	if exe, err := os.Executable(); err == nil {
		return filepath.Dir(exe)
	}
	if wd, err := os.Getwd(); err == nil {
		return wd
	}
	return "."
}

const baseEdgeYAML = `
server:
  listen: "0.0.0.0:9090"
nodes:
  - id: "node-1"
    alias: "n1"
    token: "tok-1"
    adapters:
      ollama:
        enabled: true
        base_url: "http://127.0.0.1:11434"
    providers:
      - id: "prov-a"
        type: "ollama"
        category: "local_inference"
        adapter: "ollama"
        models: ["llama3.1"]
        capacity: 2
        max_queue: 4
        queue_timeout_ms: 5000
`
