"""
Enhanced Tool Descriptions

Comprehensive descriptions for tools that help the LLM understand:
- When to use each tool
- What parameters are available
- Expected behavior and return values
- Best practices and tips

Based on OpenCode's approach to tool descriptions.
"""

# Enhanced descriptions for each tool
# These are more detailed than the basic descriptions and help
# the LLM make better decisions about when and how to use each tool.

READ_DESCRIPTION = """Reads a file from the local filesystem. You can access any file directly by using this tool.

Usage:
- The path parameter can be absolute or relative to the workspace root
- By default, it reads the entire file
- You can optionally specify offset and limit for large files
- Any lines longer than 2000 characters will be truncated
- Results include line numbers (1-indexed) for easy reference

This tool can read:
- Text files (any encoding, defaults to UTF-8)
- Image files (PNG, JPG, GIF, WebP) - returns metadata and base64 data
- PDF files - extracts text content page by page

Usage notes:
- ALWAYS read a file before editing it to understand the current content
- For large files, use offset and limit to read specific sections
- If a file doesn't exist, an error will be returned
- Prefer this tool over cat/head/tail bash commands"""


WRITE_DESCRIPTION = """Writes content to a file on the local filesystem.

Usage:
- The path parameter can be absolute or relative to the workspace root
- This tool will OVERWRITE existing files if they exist
- Parent directories will be created automatically if they don't exist

IMPORTANT:
- You MUST use the Read tool first to read the file's contents before overwriting
- ALWAYS prefer editing existing files over creating new ones
- NEVER proactively create documentation files (*.md) unless explicitly requested

Usage notes:
- Use Edit tool for making changes to existing files (safer)
- Use this tool for creating new files or completely rewriting files
- Prefer this tool over echo/cat heredoc bash commands"""


EDIT_DESCRIPTION = """Edit files with precise text replacements. This is the preferred way to modify existing files.

Usage:
- Specify the exact text to find (old_string) and its replacement (new_string)
- The old_string must be unique in the file, or the edit will fail
- Use replace_all=true to replace all occurrences of the string
- When editing text from Read tool output, preserve exact indentation

IMPORTANT:
- You MUST read the file first before editing it
- The edit will FAIL if old_string is not found or matches multiple locations
- If old_string matches multiple times, either:
  1. Provide more context to make it unique, or
  2. Use replace_all=true to change all occurrences

Best practices:
- Include enough context in old_string to ensure uniqueness
- For renaming variables, use replace_all=true
- Prefer this tool over sed/awk bash commands"""


BASH_DESCRIPTION = """Executes a shell command with optional timeout.

Usage:
- Execute terminal operations like git, npm, docker, pip, etc.
- Working directory persists between commands
- Shell state (environment variables set in commands) does not persist

IMPORTANT:
- DO NOT use this for file operations - use Read, Write, Edit tools instead
- DO NOT use grep/find - use Grep and Glob tools instead
- DO NOT use cat/head/tail - use Read tool instead
- DO NOT use sed/awk - use Edit tool instead
- DO NOT use echo to communicate - output text directly in your response

Best practices:
- Quote file paths with spaces: cd "/path/with spaces/file.txt"
- Use && to chain dependent commands: mkdir foo && cd foo
- Use ; when you need sequential execution but don't care if earlier commands fail
- Avoid using cd when possible - prefer absolute paths"""


GLOB_DESCRIPTION = """Fast file pattern matching tool that works with any codebase size.

Usage:
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns

Patterns:
- `*` - matches any characters within a single path segment
- `**` - matches any characters including path separators
- `?` - matches a single character
- `[abc]` - matches one of the characters
- `{a,b}` - matches either pattern

Examples:
- `**/*.py` - all Python files
- `src/**/*.ts` - TypeScript files in src/
- `*.{js,ts}` - JavaScript and TypeScript files in current dir

Prefer this tool over the find command."""


GREP_DESCRIPTION = """A powerful search tool built on ripgrep for searching file contents.

Usage:
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx")
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths

Parameters:
- pattern: The regex pattern to search for
- glob: Optional file pattern filter
- output_mode: "content", "files_with_matches" (default), or "count"
- -i: Case insensitive search
- -A/-B/-C: Context lines after/before/around matches

Best practices:
- Use literal braces need escaping: `interface\\{\\}` to find `interface{}`
- For multiline patterns, use multiline: true
- Prefer this tool over grep/rg bash commands"""


TODO_WRITE_DESCRIPTION = """Manage a structured task list for tracking progress.

Use this tool to:
- Create todo items for complex multi-step tasks
- Track progress on implementation work
- Break down large tasks into manageable steps
- Give the user visibility into your progress

When to use:
- Complex tasks requiring 3+ distinct steps
- User provides multiple tasks
- After receiving new instructions, capture requirements
- Before starting work, mark items as in_progress
- After completing work, mark items as completed

Task states:
- pending: Not yet started
- in_progress: Currently working on (only ONE at a time)
- completed: Task finished successfully

IMPORTANT: Mark todos completed IMMEDIATELY after finishing each task."""


TODO_READ_DESCRIPTION = """Read the current todo list to check progress.

Use this to:
- Check which tasks are pending
- See what's currently in progress
- Review completed work

Returns the todo list with item status."""


QUESTION_DESCRIPTION = """Ask the user a question to gather information or clarify requirements.

Use this tool when you:
- Need to clarify ambiguous instructions
- Want user input on implementation choices
- Need to confirm destructive actions
- Have multiple valid approaches and want user preference

Best practices:
- Only ask when truly blocked and cannot pick a reasonable default
- Don't ask permission questions like "Should I proceed?" - just proceed
- Provide options when possible to make it easy for users to respond
- Be specific and concise in your questions"""


WEBFETCH_DESCRIPTION = """Fetches content from a URL and processes it.

Usage:
- Takes a URL and optional prompt
- Fetches URL content, converts HTML to markdown
- Can process content with a prompt to extract specific information
- Includes caching (15-minute TTL)

Use this when you need to:
- Retrieve web documentation
- Get information from URLs the user provided
- Check API documentation

Notes:
- HTTP URLs will be upgraded to HTTPS
- Handles redirects (will inform you if redirect to different host)
- For GitHub URLs, prefer using gh CLI via Bash"""


WEBSEARCH_DESCRIPTION = """Search the web for information.

Usage:
- Provide a search query
- Returns search results with titles, URLs, and snippets
- Useful for finding current documentation or recent information

Best practices:
- Include the current year in queries for recent info
- Be specific in your search queries
- Verify information from multiple sources when important"""


GIT_DESCRIPTION = """Perform git operations (add, commit, push, status).

Operations:
- status: Show working tree status
- add: Stage files for commit
- commit: Create a commit with message
- push: Push to remote

IMPORTANT:
- NEVER use git commit --amend unless explicitly requested
- NEVER run force push to main/master
- NEVER skip hooks (--no-verify) unless explicitly requested
- NEVER update git config
- Create NEW commits, don't amend existing ones"""


PATCH_DESCRIPTION = """Apply unified diff patches to files.

Usage:
- Provide a unified diff patch
- Optionally specify target path
- Use dry_run=true to validate without applying
- Automatic backup creation

Best practices:
- Use for complex multi-line changes
- Prefer Edit tool for simple replacements
- Always validate with dry_run first for important changes"""


LIST_DESCRIPTION = """List directory contents with details.

Usage:
- List files and directories
- Optional recursive listing
- Filter by glob pattern
- Show hidden files optionally

Returns file/directory information including:
- Name and path
- Size
- Modification time
- Type (file or directory)"""


# Map tool names to enhanced descriptions
TOOL_DESCRIPTIONS = {
    "read": READ_DESCRIPTION,
    "write": WRITE_DESCRIPTION,
    "edit": EDIT_DESCRIPTION,
    "bash": BASH_DESCRIPTION,
    "glob": GLOB_DESCRIPTION,
    "grep": GREP_DESCRIPTION,
    "todowrite": TODO_WRITE_DESCRIPTION,
    "todoread": TODO_READ_DESCRIPTION,
    "question": QUESTION_DESCRIPTION,
    "webfetch": WEBFETCH_DESCRIPTION,
    "websearch": WEBSEARCH_DESCRIPTION,
    "git": GIT_DESCRIPTION,
    "patch": PATCH_DESCRIPTION,
    "list": LIST_DESCRIPTION,
}


def get_enhanced_description(tool_name: str, fallback: str = "") -> str:
    """
    Get the enhanced description for a tool.

    Args:
        tool_name: The tool's name
        fallback: Fallback description if tool not found

    Returns:
        Enhanced description string
    """
    return TOOL_DESCRIPTIONS.get(tool_name.lower(), fallback)
