package file

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/enmanuel/agents/internal/config"
)

func TestListDirectory_ListsFilesAndDirs(t *testing.T) {
	tmp := t.TempDir()
	os.WriteFile(filepath.Join(tmp, "file1.txt"), []byte("hello"), 0644)
	os.WriteFile(filepath.Join(tmp, "file2.txt"), []byte("world"), 0644)
	os.Mkdir(filepath.Join(tmp, "subdir"), 0755)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": tmp})
	if result.Err != nil {
		t.Fatalf("expected success, got: %v", result.Err)
	}

	if !strings.Contains(result.Output, "file1.txt") {
		t.Fatalf("expected file1.txt in output, got: %s", result.Output)
	}
	if !strings.Contains(result.Output, "file2.txt") {
		t.Fatalf("expected file2.txt in output, got: %s", result.Output)
	}
	if !strings.Contains(result.Output, "subdir") {
		t.Fatalf("expected subdir in output, got: %s", result.Output)
	}
	if !strings.Contains(result.Output, "dir") {
		t.Fatalf("expected 'dir' type in output, got: %s", result.Output)
	}
}

func TestListDirectory_Recursive(t *testing.T) {
	tmp := t.TempDir()
	sub := filepath.Join(tmp, "sub")
	os.Mkdir(sub, 0755)
	os.WriteFile(filepath.Join(tmp, "root.txt"), []byte("r"), 0644)
	os.WriteFile(filepath.Join(sub, "nested.txt"), []byte("n"), 0644)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{
		"path":      tmp,
		"recursive": true,
	})
	if result.Err != nil {
		t.Fatalf("expected success, got: %v", result.Err)
	}

	if !strings.Contains(result.Output, "root.txt") {
		t.Fatalf("expected root.txt in output, got: %s", result.Output)
	}
	if !strings.Contains(result.Output, filepath.Join("sub", "nested.txt")) {
		t.Fatalf("expected sub/nested.txt in output, got: %s", result.Output)
	}
}

func TestListDirectory_RespectsMaxEntries(t *testing.T) {
	tmp := t.TempDir()
	// Create more than maxListEntries files with unique names
	for i := 0; i < maxListEntries+10; i++ {
		name := fmt.Sprintf("file_%04d.txt", i)
		os.WriteFile(filepath.Join(tmp, name), []byte("x"), 0644)
	}

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": tmp})
	if result.Err != nil {
		t.Fatalf("expected success, got: %v", result.Err)
	}

	lines := strings.Split(result.Output, "\n")
	// Should be maxListEntries + 1 (truncation message)
	if len(lines) > maxListEntries+1 {
		t.Fatalf("expected at most %d lines, got %d", maxListEntries+1, len(lines))
	}
	if !strings.Contains(result.Output, "truncated") {
		t.Fatalf("expected truncation message, got: %s", result.Output[len(result.Output)-200:])
	}
}

func TestListDirectory_SymlinkOutsideAllowedSkipped(t *testing.T) {
	tmp := t.TempDir()
	// Create a symlink pointing outside AllowedPaths
	link := filepath.Join(tmp, "escape")
	os.Symlink("/etc", link)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": tmp})
	if result.Err != nil {
		t.Fatalf("expected success, got: %v", result.Err)
	}

	// The symlink should be skipped, not listed
	if strings.Contains(result.Output, "escape") {
		t.Fatalf("symlink pointing outside allowed paths should be skipped, got: %s", result.Output)
	}
}

func TestListDirectory_PathTraversal(t *testing.T) {
	tmp := t.TempDir()
	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{
		"path": filepath.Join(tmp, "..", "..", "etc"),
	})
	if result.Err == nil {
		t.Fatal("expected error for path traversal")
	}
}

func TestListDirectory_DenyByDefault(t *testing.T) {
	cfg := config.FileOpsCfg{AllowedPaths: []string{}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": "/tmp"})
	if result.Err == nil {
		t.Fatal("expected error when AllowedPaths is empty")
	}
}

func TestListDirectory_NotADirectory(t *testing.T) {
	tmp := t.TempDir()
	f := filepath.Join(tmp, "file.txt")
	os.WriteFile(f, []byte("hello"), 0644)

	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": f})
	if result.Err == nil {
		t.Fatal("expected error for non-directory path")
	}
	if !strings.Contains(result.Err.Error(), "not a directory") {
		t.Fatalf("expected 'not a directory' error, got: %v", result.Err)
	}
}

func TestListDirectory_EmptyPath(t *testing.T) {
	cfg := config.FileOpsCfg{AllowedPaths: []string{"/tmp"}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": ""})
	if result.Err == nil {
		t.Fatal("expected error for empty path")
	}
}

func TestListDirectory_EmptyDirectory(t *testing.T) {
	tmp := t.TempDir()
	cfg := config.FileOpsCfg{AllowedPaths: []string{tmp}}
	tool := NewListDirectory(cfg)

	result := tool.Exec(context.Background(), map[string]any{"path": tmp})
	if result.Err != nil {
		t.Fatalf("expected success for empty dir, got: %v", result.Err)
	}
	if result.Output != "" {
		t.Fatalf("expected empty output for empty dir, got: %q", result.Output)
	}
}
