"""
Copyright (C) 2024-2026 Mo Zhou <lumin@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

import difflib
import os
import pty
import re
import select
import shlex
import subprocess
import tempfile
from collections import deque

from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.text import Text

from .base import Tool, _diff_stat, _short, render_diff


class BashRunner(Tool):
    """Tool to execute arbitrary bash commands."""

    name = "bash_runner"
    description = (
        "Execute an arbitrary bash command. This always requires user confirmation."
    )

    def summary(self, args_dict: dict) -> str:
        return f"bash: {_short(args_dict.get('command', ''), 60)}"

    def needs_confirmation(self, args_dict: dict) -> tuple:
        cmd = args_dict.get("command", "")
        return True, f"Execute bash command: {cmd}"

    def __call__(self, command: str, cwd: str = ".") -> str:
        try:
            cwd = os.path.expanduser(cwd)
            if not os.path.exists(cwd):
                return f"Error: '{cwd}' does not exist."

            result = subprocess.run(
                command,
                shell=True,
                executable="/bin/bash",
                cwd=cwd,
                capture_output=True,
                text=True,
            )

            out = result.stdout
            if result.stderr:
                out += "\nSTDERR:\n" + result.stderr

            if len(out) > 4000:
                out = out[:2000] + "\n...(truncated output)...\n" + out[-2000:]

            ret = f"Status: {result.returncode}\n"
            if out.strip():
                ret += f"Output:\n{out}\n"
            else:
                ret += "No output.\n"
            return ret
        except Exception as e:
            return f"Error: {str(e)}"

    parameters = {
        "type": "object",
        "properties": {
            "command": {
                "type": "string",
                "description": "The bash command to execute.",
            },
            "cwd": {
                "type": "string",
                "description": "The current working directory. Defaults to '.'.",
            },
        },
        "required": ["command"],
    }
