//! Tool schema definitions for system operations, git, debug, wizard, and mesh tools.

use serde_json::{Value, json};

/// Returns tool schemas for system utilities, git operations, debug tools, wizard, and mesh.
pub(super) fn system_tools() -> Vec<Value> {
    vec![
        json!({
            "name": "get_server_logs",
            "description": "Return recent server log lines captured in the in-process ring buffer. Useful for diagnosing runtime behaviour such as WebSocket events, MCP call flow, and filesystem watcher activity.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "lines": {
                        "type": "integer",
                        "description": "Number of recent lines to return (default 100, max 1000)"
                    },
                    "filter": {
                        "type": "string",
                        "description": "Optional substring filter (e.g. 'watcher', 'mcp', 'permission')"
                    },
                    "severity": {
                        "type": "string",
                        "description": "Filter by severity level: ERROR, WARN, or INFO. Returns only entries at that level."
                    }
                }
            }
        }),
        json!({
            "name": "get_version",
            "description": "Return the server version, build hash, and running port.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "rebuild_and_restart",
            "description": "Rebuild the server binary from source and re-exec with the new binary. Gracefully stops all running agents before restart. If the build fails, the server stays up and returns the build error.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "prompt_permission",
            "description": "Present a permission request to the user via the web UI. Used by Claude Code's --permission-prompt-tool to delegate permission decisions to the frontend dialog. Returns on approval; returns an error on denial.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "tool_name": {
                        "type": "string",
                        "description": "The tool requesting permission (e.g. 'Bash', 'Write')"
                    },
                    "input": {
                        "type": "object",
                        "description": "The tool's input arguments"
                    }
                },
                "required": ["tool_name", "input"]
            }
        }),
        json!({
            "name": "get_token_usage",
            "description": "Return per-agent token usage records from the persistent log. Shows input tokens, output tokens, cache tokens, and cost in USD for each agent session. Optionally filter by story_id.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "story_id": {
                        "type": "string",
                        "description": "Optional: filter records to a specific story (e.g. '42_my_story')"
                    }
                }
            }
        }),
        json!({
            "name": "run_command",
            "description": "Execute a shell command in an agent's worktree directory. The working_dir must be inside .huskies/worktrees/. Returns stdout, stderr, exit_code, and timed_out. Supports SSE streaming (send Accept: text/event-stream) for long-running commands. Dangerous commands (rm -rf /, sudo, etc.) are blocked.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "The bash command to execute (passed to bash -c)"
                    },
                    "working_dir": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory to run the command in. Must be inside .huskies/worktrees/."
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Timeout in seconds (default: 120, max: 600)"
                    }
                },
                "required": ["command", "working_dir"]
            }
        }),
        json!({
            "name": "run_tests",
            "description": "Start the project's test suite (script/test) as a background job. Returns immediately with {\"status\": \"started\"}. Poll get_test_result with the same worktree_path to check for completion. If the previous run already finished, returns the result inline.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Optional absolute path to a worktree to run tests in. Must be inside .huskies/worktrees/. Defaults to the project root."
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "get_test_result",
            "description": "Check on a running test job started by run_tests. Returns {\"status\": \"running\", \"elapsed_secs\": N} if still in progress, or the full test result (passed, exit_code, test counts, output) if finished.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Optional absolute path to the worktree. Must match the worktree_path used in run_tests."
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "run_build",
            "description": "Run the project's build script (script/build) in the given worktree and return the result as truncated JSON with passed, exit_code, and output fields.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Optional absolute path to a worktree to run the build in. Must be inside .huskies/worktrees/. Defaults to the project root."
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "run_lint",
            "description": "Run the project's lint script (script/lint) in the given worktree and return the result as truncated JSON with passed, exit_code, and output fields.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Optional absolute path to a worktree to run lint in. Must be inside .huskies/worktrees/. Defaults to the project root."
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "git_status",
            "description": "Return the working tree status of an agent's worktree (staged, unstaged, and untracked files). The worktree_path must be inside .huskies/worktrees/. Push and remote operations are not available.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory. Must be inside .huskies/worktrees/."
                    }
                },
                "required": ["worktree_path"]
            }
        }),
        json!({
            "name": "git_diff",
            "description": "Return diff output for an agent's worktree. Supports unstaged (default), staged, or a commit range. The worktree_path must be inside .huskies/worktrees/.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory. Must be inside .huskies/worktrees/."
                    },
                    "staged": {
                        "type": "boolean",
                        "description": "If true, show staged diff (--staged). Default: false."
                    },
                    "commit_range": {
                        "type": "string",
                        "description": "Optional commit range (e.g. 'HEAD~3..HEAD', 'abc123..def456')."
                    }
                },
                "required": ["worktree_path"]
            }
        }),
        json!({
            "name": "git_add",
            "description": "Stage files by path in an agent's worktree. The worktree_path must be inside .huskies/worktrees/.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory. Must be inside .huskies/worktrees/."
                    },
                    "paths": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "List of file paths to stage (relative to worktree_path)."
                    }
                },
                "required": ["worktree_path", "paths"]
            }
        }),
        json!({
            "name": "git_commit",
            "description": "Commit staged changes in an agent's worktree with the given message. The worktree_path must be inside .huskies/worktrees/. Push and remote operations are not available.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory. Must be inside .huskies/worktrees/."
                    },
                    "message": {
                        "type": "string",
                        "description": "Commit message."
                    }
                },
                "required": ["worktree_path", "message"]
            }
        }),
        json!({
            "name": "git_log",
            "description": "Return commit history for an agent's worktree with configurable count and format. The worktree_path must be inside .huskies/worktrees/.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "worktree_path": {
                        "type": "string",
                        "description": "Absolute path to the worktree directory. Must be inside .huskies/worktrees/."
                    },
                    "count": {
                        "type": "integer",
                        "description": "Number of commits to return (default: 10, max: 500)."
                    },
                    "format": {
                        "type": "string",
                        "description": "git pretty-format string (default: '%H%x09%s%x09%an%x09%ai')."
                    }
                },
                "required": ["worktree_path"]
            }
        }),
        json!({
            "name": "loc_file",
            "description": "Return the line count for a specific file. Path is resolved relative to the project root. Returns an error if the file does not exist.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Path to the file, relative to the project root (e.g. 'server/src/main.rs')"
                    }
                },
                "required": ["file_path"]
            }
        }),
        json!({
            "name": "dump_crdt",
            "description": "DEBUG TOOL: Dump the raw in-memory CRDT state. Returns every item the running server knows about, including tombstoned (deleted) entries, with internal op metadata (content_index, is_deleted, stage, etc.). Use this when diagnosing CRDT/state divergence — NOT for normal pipeline introspection (use get_pipeline_status for that). Optional story_id filter returns a single item.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "story_id": {
                        "type": "string",
                        "description": "Optional: restrict output to this single work item identifier (filename stem, e.g. '42_story_my_feature')"
                    }
                },
                "required": []
            }
        }),
        json!({
            "name": "wizard_status",
            "description": "Return the current setup wizard state: which step is active, and which are done/skipped/pending. Use this to inspect progress before calling wizard_generate, wizard_confirm, wizard_skip, or wizard_retry.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "wizard_generate",
            "description": "Drive content generation for the current wizard step. Call with no arguments to mark the step as 'generating' and receive a hint about what to produce. Call again with a 'content' argument (the full file body you generated) to stage it for review. Content is NOT written to disk until wizard_confirm is called.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "content": {
                        "type": "string",
                        "description": "The generated file content to stage for the current step. Omit to receive a generation hint and mark the step as generating."
                    }
                }
            }
        }),
        json!({
            "name": "wizard_confirm",
            "description": "Confirm the current wizard step: writes any staged content to disk (only if the target file does not already exist) and advances to the next step. Existing files are never overwritten.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "wizard_skip",
            "description": "Skip the current wizard step without writing any file. Use when a step does not apply to this project.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "wizard_retry",
            "description": "Discard any staged content for the current wizard step and reset it to pending so it can be regenerated. Use when the generated content needs improvement.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
        json!({
            "name": "mesh_status",
            "description": "Return read-only peer mesh status: the local node id and a list of known peers, each with node_id, pubkey, last_seen timestamp, and is_self flag. Does not mutate state.",
            "inputSchema": {
                "type": "object",
                "properties": {}
            }
        }),
    ]
}
