package tools

import (
	"context"
	"encoding/base64"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestEncodeImageToDataURL(t *testing.T) {
	// Create a minimal 1x1 PNG
	pngBytes, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==")
	tmpPath := filepath.Join(os.TempDir(), "cyrene-test-vision.png")
	if err := os.WriteFile(tmpPath, pngBytes, 0644); err != nil {
		t.Fatalf("write test image: %v", err)
	}
	defer os.Remove(tmpPath)

	dataURL, mimeType, err := encodeImageToDataURL(tmpPath)
	if err != nil {
		t.Fatalf("encode: %v", err)
	}
	if !strings.HasPrefix(dataURL, "data:image/png;base64,") {
		t.Fatalf("unexpected data URL: %s...", dataURL[:50])
	}
	if mimeType != "image/png" {
		t.Fatalf("unexpected mime type: %s", mimeType)
	}
	t.Logf("encode OK: mime=%s, len=%d", mimeType, len(dataURL))
}

func TestEncodeImageToDataURL_InvalidPath(t *testing.T) {
	_, _, err := encodeImageToDataURL("/nonexistent/image.png")
	if err == nil {
		t.Fatal("expected error for nonexistent file")
	}
	t.Logf("error handling OK: %v", err)
}

func TestVisionToolDefinition(t *testing.T) {
	tool := NewVisionTool(nil)
	def := tool.Definition()
	if def.Name != "vision_analyze" {
		t.Fatalf("unexpected tool name: %s", def.Name)
	}
	params := def.Parameters
	props, ok := params["properties"].(map[string]interface{})
	if !ok {
		t.Fatal("missing properties")
	}
	if props["image_path"] == nil {
		t.Fatal("missing image_path parameter")
	}
	if props["task"] == nil {
		t.Fatal("missing task parameter")
	}
	t.Logf("definition OK: name=%s, params=%v", def.Name, def.Parameters)
}

func TestVisionToolExecute(t *testing.T) {
	// Create test image
	pngBytes, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==")
	tmpPath := filepath.Join(os.TempDir(), "cyrene-test-vision-exec.png")
	if err := os.WriteFile(tmpPath, pngBytes, 0644); err != nil {
		t.Fatalf("write test image: %v", err)
	}
	defer os.Remove(tmpPath)

	tool := NewVisionTool(nil)
	ctx := context.Background()
	result, err := tool.Execute(ctx, map[string]interface{}{
		"image_path": tmpPath,
		"task":       "ocr",
	})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	if !result.Success {
		t.Fatalf("execute failed: %s", result.Error)
	}
	if !strings.Contains(result.Data, "data:image/png;base64,") {
		t.Fatal("result missing data URL")
	}
	if !strings.Contains(result.Data, "ocr") {
		t.Fatal("result missing task info")
	}
	t.Logf("execute OK: data len=%d", len(result.Data))
}
