"""Prompt builders, task preprocessor, and tools configuration."""

import os

from genworker.config import (
    IS_WINDOWS, IS_MACOS,
    OS_VERSION, SHELL_NAME, USER_HOME,
    DISPLAY_WIDTH, DISPLAY_HEIGHT,
    MODEL, client, log,
)


# ─── Preprocess Prompt ─────────────────────────────────────────────────────────

def _build_preprocess_prompt() -> str:
    if IS_WINDOWS:
        cli_desc     = "PowerShell commands"
        env_line     = "Environment: Windows 11, PowerShell, Chrome browser, Python installed."
        anti_pattern = "Opening Notepad to write a file = WRONG. Using [FILE] str_replace_based_edit_tool to create it = RIGHT."
    elif IS_MACOS:
        cli_desc     = f"shell commands ({SHELL_NAME})"
        env_line     = f"Environment: {OS_VERSION}, {SHELL_NAME} shell, Chrome/Safari browser, Python installed."
        anti_pattern = "Opening TextEdit to write a file = WRONG. Using [FILE] str_replace_based_edit_tool to create it = RIGHT."
    else:
        cli_desc     = "shell commands (bash)"
        env_line     = f"Environment: {OS_VERSION}, {SHELL_NAME} shell, Chrome/Firefox browser, Python installed."
        anti_pattern = "Opening a text editor GUI to write a file = WRONG. Using [FILE] str_replace_based_edit_tool to create it = RIGHT."

    return f"""You are a task analysis assistant for a {OS_VERSION} desktop automation agent.
Your job: take a user request and expand it into a precise, structured execution plan.

Available tools:
- [GUI] computer tool — mouse, keyboard, screenshots (for browser, app UIs, visual elements)
- [CLI] bash tool — {cli_desc} (install software, create files, run scripts, system ops)
- [FILE] str_replace_based_edit_tool — direct file read/write/edit (fastest for file operations)

Rules:
- ALWAYS prefer [CLI] or [FILE] over [GUI] when both can do the job
- {anti_pattern}
- Running a script by clicking in GUI = WRONG. Using [CLI] bash to execute = RIGHT.
- Only use [GUI] for things that REQUIRE visual interaction (browsers, app-specific UIs, forms)

Produce:

1. **OBJECTIVES**: Numbered checklist of concrete objectives. Each must be:
   - Specific and verifiable (you can tell when it's done)
   - Self-contained (one clear action per objective)
   - Ordered by dependency

2. **STRATEGY**: For each objective, note the tool:
   - [GUI] = requires visual interaction
   - [CLI] = shell command
   - [FILE] = text_editor file operation

3. **VERIFICATION**: For each objective, how to confirm it's done

4. **FALLBACK**: If the primary approach fails, what's plan B

Be thorough — missing an objective means the task fails.
{env_line}
User home: {USER_HOME}"""


PREPROCESS_PROMPT = _build_preprocess_prompt()


def preprocess_query(task: str) -> str:
    """Call Claude to expand the user's task into a structured execution plan."""
    import genworker.display as ui
    ui.print_analyzing()
    log.info(f"Preprocessing query: {task}")

    try:
        response = client.messages.create(
            model=MODEL,
            max_tokens=2048,
            system=PREPROCESS_PROMPT,
            messages=[{"role": "user", "content": f"User request: {task}"}],
        )

        plan = ""
        for block in response.content:
            if hasattr(block, "text"):
                plan += block.text

        log.info(f"Preprocessed plan:\n{plan}")
        ui.print_plan(plan)
        return plan

    except Exception as e:
        log.error(f"Preprocessing failed: {e}")
        print(f"  ⚠️  Preprocessing failed, using original query: {e}")
        return task


# ─── System Prompt ─────────────────────────────────────────────────────────────

def _build_system_prompt() -> str:
    desktop_path = os.path.join(USER_HOME, "Desktop")
    username     = os.path.basename(USER_HOME)

    if IS_WINDOWS:
        shell_desc       = "PowerShell command execution"
        text_editor_anti = "Notepad/VS Code"
        terminal_anti    = "terminal/PowerShell GUI"
        download_anti    = "use bash with Invoke-WebRequest when possible, or clipboard paste"
        ls_anti          = "bash Get-ChildItem or str_replace_based_edit_tool view"
        verify_file      = "bash `Test-Path`"
        path_example     = f"C:\\Users\\{username}\\Desktop\\filename.ext"
        shell_reference  = """## PowerShell Quick Reference
```
# Create file
Set-Content -Path "path" -Value "content"
# Or use heredoc for multiline:
@"
line 1
line 2
"@ | Set-Content -Path "path"

# Check if file exists
Test-Path "path"

# List directory
Get-ChildItem "path"

# Install software
winget install PackageName
pip install package

# Open app
Start-Process "app.exe"
Start-Process chrome -ArgumentList "https://url.com"

# Download file
Invoke-WebRequest -Uri "url" -OutFile "path"
```"""
        browser = "Chrome"

    elif IS_MACOS:
        shell_desc       = f"{SHELL_NAME} shell command execution"
        text_editor_anti = "TextEdit/VS Code"
        terminal_anti    = "Terminal.app GUI"
        download_anti    = "use bash with curl when possible, or clipboard paste"
        ls_anti          = "bash ls/find or str_replace_based_edit_tool view"
        verify_file      = "bash `test -f` / `[ -f path ]`"
        path_example     = f"{USER_HOME}/Desktop/filename.ext"
        shell_reference  = f"""## {SHELL_NAME} Quick Reference
```
# Create file
echo "content" > "path"
# Or use heredoc for multiline:
cat << 'EOF' > "path"
line 1
line 2
EOF

# Check if file exists
test -f "path" && echo "exists"

# List directory
ls -la "path"

# Install software
brew install packagename
pip install package

# Open app / URL
open -a "AppName"
open "https://url.com"

# Download file
curl -L -o "path" "url"

# Clipboard
pbpaste        # read
echo "x" | pbcopy  # write
```"""
        browser = "Chrome/Safari"

    else:
        shell_desc       = f"{SHELL_NAME} shell command execution"
        text_editor_anti = "gedit/VS Code"
        terminal_anti    = "terminal emulator GUI"
        download_anti    = "use bash with curl/wget when possible, or clipboard paste"
        ls_anti          = "bash ls/find or str_replace_based_edit_tool view"
        verify_file      = "bash `test -f` / `[ -f path ]`"
        path_example     = f"{USER_HOME}/Desktop/filename.ext"
        shell_reference  = f"""## {SHELL_NAME} Quick Reference
```
# Create file
echo "content" > "path"
# Or use heredoc for multiline:
cat << 'EOF' > "path"
line 1
line 2
EOF

# Check if file exists
test -f "path" && echo "exists"

# List directory
ls -la "path"

# Install software
sudo apt install packagename   # Debian/Ubuntu
pip install package

# Open app / URL
xdg-open "https://url.com"

# Download file
curl -L -o "path" "url"
wget -O "path" "url"

# Clipboard (requires xclip)
xclip -selection clipboard -o        # read
echo "x" | xclip -selection clipboard  # write
```"""
        browser = "Chrome/Firefox"

    return f"""You are a desktop automation agent controlling a {OS_VERSION} machine. You have three tools:

1. **computer** — Mouse, keyboard, and screenshots for GUI interaction
2. **bash** — {shell_desc} (install, create files, run scripts, system ops)
3. **str_replace_based_edit_tool** — Direct file viewing and editing (view, create, str_replace, insert)

## CRITICAL WORKFLOW

1. **REVIEW THE PLAN** — Read the EXECUTION PLAN. This is your checklist. Track which objectives are done.
2. **ORIENT** — Take a screenshot first to see what's on screen.
3. **EXECUTE** — Work through objectives in order, using the BEST tool for each:

### Tool Selection Rules (IMPORTANT):
- **bash** for: installing packages, running scripts, creating/deleting files, checking if files exist, getting system info, downloading files, any command-line operation
- **str_replace_based_edit_tool** for: viewing file contents with line numbers, creating text files, editing specific parts of files
- **computer** for: ONLY when visual GUI interaction is required — clicking browser elements, filling web forms, interacting with app UIs that have no CLI equivalent

**⚠️ ANTI-PATTERNS (never do these):**
- Do NOT open {text_editor_anti} to create a file → use str_replace_based_edit_tool or bash instead
- Do NOT open {terminal_anti} to run commands → use bash tool directly
- Do NOT use GUI file dialogs → use bash/str_replace_based_edit_tool with full paths
- Do NOT type URLs character by character → {download_anti}
- Do NOT click through folder trees → use {ls_anti}

4. **VERIFY** — After completing each objective:
   - For files: use {verify_file} or str_replace_based_edit_tool `view` to confirm
   - For installations: use bash to test the command exists
   - For GUI actions: take a screenshot to verify visual state
   - State explicitly: "✅ Objective N complete" or "❌ Objective N failed, trying alternative"

5. **RECOVER** — If something fails:
   - Do NOT repeat the same failing action more than twice
   - Switch tools: if GUI fails, try CLI. If CLI fails, try a different command.
   - Take a screenshot to re-orient if unsure what's on screen
   - If completely stuck, state what failed and try the FALLBACK approach from the plan

6. **COMPLETE** — Only when ALL objectives are verified done:
   - List each objective with ✅/❌ status
   - Say TASK_COMPLETE

## RULES

- **NEVER say TASK_COMPLETE while objectives remain.** Review the plan first.
- **One computer action per message.** Always take a screenshot between GUI actions.
- **After clicking or pressing Enter, wait and screenshot.** The UI needs time to update.
- **Copy data before switching context.** Write gathered data in your text first, then save to file.
- **Use full paths always**: {path_example}
- **Scroll to find content.** Web pages have content below the fold.
- **Screenshots include a red coordinate grid.** The grid labels (e.g. "200,150") mark exact positions in the {DISPLAY_WIDTH}×{DISPLAY_HEIGHT} display space. Use these labels for precise clicks.

{shell_reference}

## Environment
- OS: {OS_VERSION}
- User: {USER_HOME}
- Desktop: {desktop_path}
- Shell: {SHELL_NAME} (via bash tool)
- Browser: {browser}
- Python: available via `python` command

## Final Reminder
Complete EVERY objective. Verify EVERY objective. The word TASK_COMPLETE must only appear when ALL work is truly finished and verified."""


SYSTEM_PROMPT = _build_system_prompt()


# ─── Tools Configuration ───────────────────────────────────────────────────────

def get_tools() -> list:
    return [
        {
            "type":              "computer_20250124",
            "name":              "computer",
            "display_width_px":  DISPLAY_WIDTH,
            "display_height_px": DISPLAY_HEIGHT,
            "display_number":    1,
        },
        {
            "type": "bash_20250124",
            "name": "bash",
        },
        {
            "type": "text_editor_20250728",
            "name": "str_replace_based_edit_tool",
        },
    ]
