package mcp

// ToolDescription provides enhanced descriptions for AI agents
type ToolDescription struct {
	Description string
	WhenToUse   []string
	DoNotUse    []string // Optional: When NOT to use this tool
	Examples    []string
	NextTools   []string
}

// Enhanced tool descriptions for better AI discoverability
var toolDescriptions = map[string]ToolDescription{
	"worktree_add": {
		Description: "Add a new isolated git worktree for development. Each worktree has its own branch and can be used for working on separate features or issues",
		WhenToUse: []string{
			"When starting work on a new feature or bug fix",
			"When you need an isolated environment to test changes",
			"When asked to 'work on issue #X' or 'implement feature Y'",
			"Before making any code changes to the repository",
			"When you want to experiment without affecting the main branch",
		},
		Examples: []string{
			`worktree_add(name: "fix-issue-30") → {branch: "fix-issue-30", path: "/path/to/worktree"}`,
			`worktree_add(name: "feat-api", description: "New API endpoints") → {branch: "feat-api", description: "New API endpoints"}`,
			`worktree_add(name: "hotfix", baseBranch: "release/v2") → {branch: "hotfix", base_branch: "release/v2"}`,
		},
		NextTools: []string{
			"resource_worktree_browse - Explore the worktree structure",
			"session_run - Run tests or build commands",
		},
	},

	"worktree_remove": {
		Description: "Remove a worktree and its working directory. This permanently deletes the worktree directory and cannot be undone",
		WhenToUse: []string{
			"After a pull request has been merged",
			"When cleaning up abandoned or experimental worktrees",
			"When explicitly asked to remove or delete a worktree",
			"After completing work on a feature or fix",
		},
		Examples: []string{
			`worktree_remove(worktree_identifier: "fix-issue-30") → {message: "Worktree fix-issue-30 removed"}`,
			`worktree_remove(worktree_identifier: "feat-api") → {message: "Worktree feat-api removed"}`,
		},
		NextTools: []string{
			"resource_worktree_list - Verify remaining worktrees",
			"worktree_add - Create a new worktree for the next task",
		},
	},

	"resource_worktree_browse": {
		Description: "Browse files in a worktree (replaces ls, find, tree commands). Returns directory listings or file contents. FASTER than bash commands and provides better context",
		WhenToUse: []string{
			"When you need to explore project structure",
			"When looking for specific files or understanding code organization",
			"Instead of using bash commands like 'ls', 'find', or 'tree'",
			"Before making changes to understand existing code patterns",
			"When asked 'what files are in X directory?'",
			"To check if a file or directory exists",
		},
		Examples: []string{
			`resource_worktree_browse(worktree_identifier: "fix-auth") → {content: "src/\nREADME.md\ngo.mod\n..."}`,
			`resource_worktree_browse(worktree_identifier: "fix-auth", path: "src/") → {content: "main.go\nconfig/\nhandlers/\n..."}`,
			`resource_worktree_browse(worktree_identifier: "fix-auth", path: "README.md") → {content: "# Project Title\n\nDescription..."}`,
		},
		NextTools: []string{
			"session_run - Execute commands in the worktree",
		},
	},

	"session_run": {
		Description: "Run an AI agent session for LONG-RUNNING or INTERACTIVE processes. Creates and manages persistent sessions with proper lifecycle control",
		WhenToUse: []string{
			"Long-running processes (dev servers, watchers, builds)",
			"Interactive programs requiring input (REPL, debuggers)",
			"Test suites that take >30 seconds",
			"Background tasks that need monitoring",
		},
		DoNotUse: []string{
			"One-off commands that complete immediately (git, make, npm install, etc.)",
			"Simple file operations (creating, reading, listing files)",
			"Any command that exits after completion",
		},
		Examples: []string{
			`session_run(agent_id: "test", command: "npm run dev", worktree_identifier: "fix-auth") → {id: "session-123", status: "running"}`,
			`session_run(agent_id: "python", command: "python -m pytest --watch", worktree_identifier: "feat-api") → {id: "session-124", status: "running"}`,
			`❌ BAD: session_run(agent_id: "shell", command: "git status", worktree_identifier: "fix-bug") → Use Bash tool instead`,
			`❌ BAD: session_run(agent_id: "shell", command: "npm install", worktree_identifier: "feat-test") → Use Bash tool instead`,
		},
		NextTools: []string{
			"resource_session_output - Monitor the command output",
			"session_send_input - Send input if the command is interactive",
			"session_storage_write - Save important output or results",
			"session_stop - Stop the session when done",
		},
	},

	"resource_session_output": {
		Description: "Read session output/logs. Essential for monitoring command execution and debugging",
		WhenToUse: []string{
			"After running session_run to see command results",
			"To check for errors or test failures",
			"To monitor long-running processes",
			"When debugging issues to see detailed output",
			"To verify that commands completed successfully",
		},
		Examples: []string{
			`resource_session_output(session_identifier: "session-123") → {content: "Running tests...\nPASS: auth_test.go\nPASS: main_test.go\n"}`,
			`resource_session_output(session_identifier: "1") → {content: "[ERROR] Build failed: undefined variable\n"}`,
		},
		NextTools: []string{
			"session_send_input - Send commands if errors need fixing",
			"session_storage_write - Document important findings",
			"session_stop - Stop the session if needed",
		},
	},

	"session_send_input": {
		Description: "Send input text to a running agent session's stdin. Use for interactive commands",
		WhenToUse: []string{
			"When a session is waiting for user input",
			"To answer prompts from interactive commands",
			"To send commands to a REPL or shell session",
			"When debugging interactively",
		},
		Examples: []string{
			`session_send_input(session_identifier: "session-123", input: "yes\n") → {message: "Input sent to session session-123"}`,
			`session_send_input(session_identifier: "2", input: "exit\n") → {message: "Input sent to session 2"}`,
		},
		NextTools: []string{
			"resource_session_output - Check the response",
			"session_stop - Stop when done with interaction",
		},
	},

	"session_stop": {
		Description: "Stop a running agent session gracefully",
		WhenToUse: []string{
			"When a command has completed its task",
			"To clean up long-running or stuck sessions",
			"Before removing a worktree",
			"When explicitly asked to stop a session",
		},
		Examples: []string{
			`session_stop(session_identifier: "session-123") → {message: "Session session-123 stopped successfully"}`,
			`session_stop(session_identifier: "1") → {message: "Session 1 stopped successfully"}`,
		},
		NextTools: []string{
			"resource_session_list - Check remaining sessions",
			"worktree_remove - Clean up the worktree if done",
		},
	},

	"session_list": {
		Description: "List all sessions or sessions in a specific worktree",
		WhenToUse: []string{
			"To see all active sessions across worktrees",
			"To check session status and health",
			"Before creating new sessions to avoid duplicates",
			"To find specific sessions by worktree",
		},
		Examples: []string{
			`session_list() → [{session_id: "session-1", worktree_id: "fix-bug", status: "running", command: ["npm", "run", "dev"]}]`,
			`session_list(worktree_id: "fix-auth") → [{session_id: "session-2", status: "stopped", exit_code: 0}]`,
		},
		NextTools: []string{
			"session_logs - Check logs from specific sessions",
			"session_stop - Stop unnecessary sessions",
			"session_remove - Clean up stopped sessions",
		},
	},

	"session_logs": {
		Description: "Get logs from a session",
		WhenToUse: []string{
			"To check output from a running or completed session",
			"To debug issues with a failed session",
			"To monitor progress of long-running tasks",
			"To retrieve test results or build output",
		},
		Examples: []string{
			`session_logs(session_id: "session-123") → {logs: "[INFO] Starting build...\n[INFO] Build completed successfully"}`,
			`session_logs(session_id: "session-123", follow: true) → {logs: "...", note: "Logs are truncated to 64KB. Use CLI for full logs"}`,
		},
		NextTools: []string{
			"session_stop - Stop the session if needed",
			"session_storage_read - Read full logs from storage",
		},
	},

	"session_remove": {
		Description: "Remove a stopped session and clean up its resources",
		WhenToUse: []string{
			"After a session has completed or been stopped",
			"To clean up old session data",
			"When session is no longer needed",
			"To free up system resources",
		},
		Examples: []string{
			`session_remove(session_id: "session-123") → {message: "Session session-123 removed"}`,
			`session_remove(session_id: "2") → {message: "Session 2 removed"}`,
		},
		NextTools: []string{
			"resource_session_list - Check remaining sessions",
			"session_run - Start a new session if needed",
		},
	},

	"resource_worktree_list": {
		Description: "List all worktrees. Shows branch name, path, and other details",
		WhenToUse: []string{
			"To see all available worktrees",
			"When starting work to choose or create a worktree",
			"To find a specific worktree by branch name",
			"To check worktree status before operations",
		},
		Examples: []string{
			`resource_worktree_list() → [{branch: "fix-auth", path: "/path/to/fix-auth"}, {branch: "feat-api", path: "/path/to/feat-api"}]`,
		},
		NextTools: []string{
			"resource_worktree_show - Get details of a specific worktree",
			"worktree_add - Create a new worktree if needed",
			"resource_worktree_browse - Explore a worktree",
		},
	},

	"resource_worktree_show": {
		Description: "Get detailed information about a specific worktree",
		WhenToUse: []string{
			"To get the full path of a worktree",
			"To check worktree metadata and status",
			"To verify worktree configuration",
			"Before performing operations on a worktree",
		},
		Examples: []string{
			`resource_worktree_show(worktree_identifier: "fix-auth") → {branch: "fix-auth", path: "/path/to/worktree", base_branch: "main"}`,
			`resource_worktree_show(worktree_identifier: "feat-api") → {branch: "feat-api", description: "API refactoring", created_at: "2024-01-15T10:30:00Z"}`,
		},
		NextTools: []string{
			"resource_worktree_browse - Explore the worktree files",
			"session_run - Execute commands in the worktree",
		},
	},

	"resource_session_list": {
		Description: "List all active sessions with their status",
		WhenToUse: []string{
			"To see what sessions are running",
			"To find a specific session ID",
			"To check session status (busy/idle/stuck)",
			"Before creating new sessions",
		},
		Examples: []string{
			`resource_session_list() → [{id: "session-123", name: "test", status: "running", worktree_id: "fix-auth"}, {id: "session-124", status: "idle", worktree_id: "feat-api"}]`,
		},
		NextTools: []string{
			"resource_session_show - Get session details",
			"resource_session_output - Check session output",
			"session_stop - Stop unneeded sessions",
		},
	},

	"resource_session_show": {
		Description: "Get detailed information about a specific session",
		WhenToUse: []string{
			"To check session configuration",
			"To verify session status and health",
			"To get session metadata",
		},
		Examples: []string{
			`resource_session_show(session_identifier: "session-123") → {id: "session-123", agent_id: "test", status: "running", command: "go test", started_at: "2024-01-15T10:35:00Z"}`,
		},
		NextTools: []string{
			"resource_session_output - Check session logs",
			"session_send_input - Interact with the session",
			"session_stop - Stop if needed",
		},
	},

	// New separated storage tools

	"session_storage_read": {
		Description: "Read files from session storage. Use this to read session-specific output and logs",
		WhenToUse: []string{
			"When you need to read session output files",
			"To examine logs, test results, or command output",
			"After a session has written output to storage",
			"To debug issues by reading session logs",
		},
		Examples: []string{
			`session_storage_read(session_identifier: "session-123", path: "output.log") → {content: "[INFO] Starting...\n[ERROR] Failed...", size: 1024}`,
			`session_storage_read(session_identifier: "2", path: "test-results.json") → {content: "{\"passed\": 10, \"failed\": 2}", size: 156}`,
		},
		NextTools: []string{
			"session_storage_write - Update session files",
			"session_storage_list - Find other session files",
			"resource_session_output - Check live session output",
		},
	},

	"session_storage_write": {
		Description: "Write files to session storage. Use this to save session-specific data",
		WhenToUse: []string{
			"When saving session-specific output or results",
			"To persist command output for later analysis",
			"To create session logs or reports",
			"When debugging to save intermediate results",
		},
		Examples: []string{
			`session_storage_write(session_identifier: "session-123", path: "results.json", content: "{...}") → {path: "results.json", bytes: 156}`,
			`session_storage_write(session_identifier: "2", path: "debug.log", content: "Debug info...") → {path: "debug.log", bytes: 512}`,
		},
		NextTools: []string{
			"session_storage_read - Verify the file was written",
			"session_storage_list - See all session files",
			"resource_session_output - Check session status",
		},
	},

	"session_storage_list": {
		Description: "List files in session storage",
		WhenToUse: []string{
			"To see what files exist in session storage",
			"To find logs, output files, or results",
			"Before reading session files",
			"To verify session output was saved",
		},
		Examples: []string{
			`session_storage_list(session_identifier: "session-123") → {files: ["output.log", "errors.log", "results/"], count: 3}`,
			`session_storage_list(session_identifier: "2", path: "logs/") → {files: ["test.log", "build.log"], count: 2}`,
		},
		NextTools: []string{
			"session_storage_read - Read specific files",
			"session_storage_write - Create new files",
			"resource_session_output - Check live output",
		},
	},
}

// GetEnhancedDescription returns the enhanced description for a tool
func GetEnhancedDescription(toolName string) string {
	if desc, ok := toolDescriptions[toolName]; ok {
		result := desc.Description + "\n\nWHEN TO USE THIS TOOL:\n"
		for _, when := range desc.WhenToUse {
			result += "- " + when + "\n"
		}

		if len(desc.DoNotUse) > 0 {
			result += "\nDO NOT USE FOR:\n"
			for _, doNot := range desc.DoNotUse {
				result += "- " + doNot + "\n"
			}
		}

		if len(desc.Examples) > 0 {
			result += "\nEXAMPLES:\n"
			for _, example := range desc.Examples {
				result += example + "\n"
			}
		}

		return result
	}
	return ""
}

// GetNextToolSuggestions returns suggested next tools for a given tool
func GetNextToolSuggestions(toolName string) []map[string]string {
	if desc, ok := toolDescriptions[toolName]; ok {
		suggestions := make([]map[string]string, 0, len(desc.NextTools))
		for _, next := range desc.NextTools {
			suggestions = append(suggestions, map[string]string{
				"tool": next,
			})
		}
		return suggestions
	}
	return nil
}
