"""
Tree generation for FileManager V2.

Generates directory tree visualizations with:
- Max depth limiting
- Max items per directory
- Permission error handling
- ASCII tree connectors (├── └──)
"""

from pathlib import Path
from typing import List


class TreeGenerator:
    """Generate directory tree visualization."""

    def generate_tree(self, path: str, max_depth: int = 3, max_items: int = 20) -> str:
        """
        Generate tree structure as text.

        Args:
            path: Directory path to generate tree for
            max_depth: Maximum depth to traverse
            max_items: Maximum items per directory

        Returns:
            Tree visualization as string
        """
        tree_lines = []

        def walk_tree(current_path: Path, prefix: str = "", depth: int = 0):
            """
            Recursively walk tree and build visualization.

            Args:
                current_path: Current directory path
                prefix: Line prefix for indentation
                depth: Current depth level
            """
            if depth >= max_depth:
                return

            try:
                # Get items sorted (directories first)
                items = sorted(
                    current_path.iterdir(),
                    key=lambda p: (not p.is_dir(), p.name)
                )

                # Limit items
                items = items[:max_items]

                for i, item in enumerate(items):
                    is_last = i == len(items) - 1
                    connector = "└── " if is_last else "├── "

                    if item.is_dir():
                        # Directory
                        tree_lines.append(f"{prefix}{connector}{item.name}/")

                        # Recurse into directory
                        extension = "    " if is_last else "│   "
                        walk_tree(item, prefix + extension, depth + 1)
                    else:
                        # File
                        tree_lines.append(f"{prefix}{connector}{item.name}")

            except PermissionError:
                tree_lines.append(f"{prefix}[Permission Denied]")

        # Start with root
        root_path = Path(path)
        tree_lines.append(f"{root_path.name}/")
        walk_tree(root_path, "", 0)

        return '\n'.join(tree_lines)

    def generate_tree_with_tokens(self, path: str, file_blocks: dict, max_depth: int = 3, max_items: int = 20) -> str:
        """
        Generate tree with token counts from FileBlock data.

        Args:
            path: Directory path
            file_blocks: Dict of path -> FileBlock
            max_depth: Maximum depth
            max_items: Maximum items per directory

        Returns:
            Tree visualization with token counts
        """
        tree_lines = []

        def walk_tree(current_path: Path, prefix: str = "", depth: int = 0):
            if depth >= max_depth:
                return

            try:
                items = sorted(
                    current_path.iterdir(),
                    key=lambda p: (not p.is_dir(), p.name)
                )
                items = items[:max_items]

                for i, item in enumerate(items):
                    is_last = i == len(items) - 1
                    connector = "└── " if is_last else "├── "

                    if item.is_dir():
                        tree_lines.append(f"{prefix}{connector}{item.name}/")
                        extension = "    " if is_last else "│   "
                        walk_tree(item, prefix + extension, depth + 1)
                    else:
                        # Check if we have FileBlock data for this file
                        file_path_str = str(item.resolve())
                        if file_path_str in file_blocks:
                            file_block = file_blocks[file_path_str]
                            tree_lines.append(f"{prefix}{connector}{item.name} ({file_block.tokens} tokens)")
                        else:
                            tree_lines.append(f"{prefix}{connector}{item.name}")

            except PermissionError:
                tree_lines.append(f"{prefix}[Permission Denied]")

        root_path = Path(path)
        tree_lines.append(f"{root_path.name}/")
        walk_tree(root_path, "", 0)

        return '\n'.join(tree_lines)
