"""List files in a directory.

Returns a list of files and directories in the specified path.
"""

from pathlib import Path

from core.pathways.models.tool import ToolOutput


async def run(
    path: str = ".",
    pattern: str = "*",
    recursive: bool = False,
    include_hidden: bool = False,
    max_results: int = 200,
) -> ToolOutput:
    """
    Args:
        path: Directory path to list (default: current directory)
        pattern: Glob pattern to filter files (default: *)
        recursive: Whether to search recursively
        include_hidden: Whether to include hidden files (starting with .)
        max_results: Maximum number of entries to return (default: 200).
    """
    try:
        dir_path = Path(path).expanduser().resolve()

        if not dir_path.exists():
            return ToolOutput(success=False, error=f"Directory not found: {path}")

        if not dir_path.is_dir():
            return ToolOutput(success=False, error=f"Not a directory: {path}")

        matches = dir_path.rglob(pattern) if recursive else dir_path.glob(pattern)

        files: list[dict[str, object]] = []
        dirs: list[dict[str, object]] = []
        truncated = False
        total_seen = 0

        for item in sorted(matches):
            # Skip hidden files unless requested
            if not include_hidden and item.name.startswith("."):
                continue

            total_seen += 1
            if total_seen > max_results:
                truncated = True
                break

            rel_path = str(item.relative_to(dir_path))

            if item.is_file():
                files.append(
                    {
                        "name": item.name,
                        "path": rel_path,
                        "size": item.stat().st_size,
                    },
                )
            elif item.is_dir():
                dirs.append(
                    {
                        "name": item.name,
                        "path": rel_path,
                    },
                )

        data: dict[str, object] = {
            "path": str(dir_path),
            "files": files,
            "directories": dirs,
            "total_files": len(files),
            "total_directories": len(dirs),
        }
        if truncated:
            data["truncated"] = True
            data["max_results"] = max_results

        return ToolOutput(success=True, data=data)

    except PermissionError:
        return ToolOutput(success=False, error=f"Permission denied: {path}")
    except Exception as e:
        return ToolOutput(success=False, error=str(e))
