"""
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 DirectoryLister(Tool):
    """Tool to list directory contents (like the ls command)."""

    name = "directory_lister"
    description = (
        "List the contents of a directory. Supports options for "
        "showing hidden files, long format with details, and "
        "recursive listing."
    )

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

    def __call__(
        self,
        path: str = ".",
        all: bool = False,
        long: bool = False,
        recursive: bool = False,
    ) -> str:
        try:
            path = os.path.expanduser(path)
            if not os.path.exists(path):
                return f"Error: '{path}' does not exist."
            if not os.path.isdir(path):
                return f"Error: '{path}' is not a directory."

            cmd = ["ls"]
            if all:
                cmd.append("-a")
            if long:
                cmd.append("-lh")
            if recursive:
                cmd.append("-R")
            cmd.append(path)

            result = subprocess.run(cmd, capture_output=True, text=True)
            if result.returncode != 0:
                return f"Error: {result.stderr.strip()}"
            return result.stdout
        except Exception as e:
            return f"Error: {str(e)}"

    parameters = {
        "type": "object",
        "properties": {
            "path": {
                "type": "string",
                "description": "Path to the directory to list. "
                "Defaults to the current directory.",
            },
            "all": {
                "type": "boolean",
                "description": "If true, include hidden files "
                "(those starting with '.'). "
                "Defaults to false.",
            },
            "long": {
                "type": "boolean",
                "description": "If true, use long listing format "
                "showing permissions, size, and "
                "modification time. Defaults to "
                "false.",
            },
            "recursive": {
                "type": "boolean",
                "description": "If true, list subdirectories "
                "recursively. Defaults to false.",
            },
        },
        "required": [],
    }
