package tools

import (
	"context"
	"os"
	"strings"
	"testing"

	"git.yeij.top/AskaEth/Cyrene/ai-core/internal/host"
)

func TestOSExecToolWSL(t *testing.T) {
	distro := os.Getenv("WSL_DISTRO")
	if distro == "" {
		t.Skip("WSL_DISTRO not set, skipping OS tool integration test")
	}
	backend := host.NewWSLBackend(distro, "cyrene", "test123", 30e9)
	mgr := host.NewManager(backend)

	// Test os_exec
	t.Run("os_exec", func(t *testing.T) {
		tool := NewOSExecTool(mgr)
		def := tool.Definition()
		if def.Name != "os_exec" {
			t.Fatalf("unexpected name: %s", def.Name)
		}
		result, err := tool.Execute(context.Background(), map[string]interface{}{
			"command": "echo 'os_exec works!' && uname -a",
		})
		if err != nil {
			t.Fatalf("execute error: %v", err)
		}
		if !result.Success {
			t.Fatalf("exec failed: %s", result.Error)
		}
		if !strings.Contains(result.Data, "os_exec works!") {
			t.Fatalf("unexpected output: %s", result.Data)
		}
		t.Logf("os_exec OK: data len=%d", len(result.Data))
	})

	// Test os_file
	t.Run("os_file", func(t *testing.T) {
		tool := NewOSFileTool(mgr)
		def := tool.Definition()
		if def.Name != "os_file" {
			t.Fatalf("unexpected name: %s", def.Name)
		}

		// Write
		r, err := tool.Execute(context.Background(), map[string]interface{}{
			"action":  "write",
			"path":    "/tmp/cyrene-os-tool-test.txt",
			"content": "OS tool integration test",
		})
		if err != nil || !r.Success {
			t.Fatalf("os_file write failed: err=%v, errMsg=%s", err, r.Error)
		}

		// Read
		r, err = tool.Execute(context.Background(), map[string]interface{}{
			"action": "read",
			"path":   "/tmp/cyrene-os-tool-test.txt",
		})
		if err != nil || !r.Success {
			t.Fatalf("os_file read failed: err=%v, errMsg=%s", err, r.Error)
		}
		if !strings.Contains(r.Data, "OS tool integration test") {
			t.Fatalf("content mismatch: %s", r.Data)
		}

		// List
		r, err = tool.Execute(context.Background(), map[string]interface{}{
			"action": "list",
			"path":   "/tmp",
		})
		if err != nil || !r.Success {
			t.Fatalf("os_file list failed: err=%v, errMsg=%s", err, r.Error)
		}
		t.Logf("os_file OK: write+read+list all pass")
	})

	// Test os_system
	t.Run("os_system", func(t *testing.T) {
		tool := NewOSSystemTool(mgr)
		def := tool.Definition()
		if def.Name != "os_system" {
			t.Fatalf("unexpected name: %s", def.Name)
		}
		result, err := tool.Execute(context.Background(), map[string]interface{}{})
		if err != nil {
			t.Fatalf("execute error: %v", err)
		}
		if !result.Success {
			t.Fatalf("os_system failed: %s", result.Error)
		}
		if !strings.Contains(result.Data, "wsl") {
			t.Fatalf("expected wsl backend info: %s", result.Data)
		}
		t.Logf("os_system OK: data len=%d", len(result.Data))
	})
}
