"""
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 ManPageReader(Tool):
    """Tool to read man pages."""

    name = "man_page_reader"
    description = "Reads a man page for a given command."

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

    def __call__(self, command: str) -> str:
        try:
            # We use PAGER=cat to avoid interactive pagination
            result = subprocess.run(
                ["man", command],
                env={"PAGER": "cat", "MANPAGER": "cat", "LC_ALL": "C"},
                capture_output=True,
                text=True,
            )
            if result.returncode != 0:
                return f"Error reading man page for {command}: {result.stderr.strip()}"

            # Remove overstriking (e.g., '_\x08x' -> 'x', 'x\x08x' -> 'x')
            text = re.sub(r".\x08", "", result.stdout)
            return text
        except Exception as e:
            return f"Error: {str(e)}"

    parameters = {
        "type": "object",
        "properties": {
            "command": {
                "type": "string",
                "description": "The command to read the manual page for.",
            }
        },
        "required": ["command"],
    }
