"""
Progress display wrapper for TTY and non-TTY environments.

Provides Rich Progress in TTY environments and simple logging in containers.
Follows CLAUDE.md: Single responsibility, <50 lines/method.
"""

import sys
from typing import Optional, Any
from contextlib import contextmanager
from rich.progress import Progress as RichProgress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.console import Console

from .environment_detection import should_use_progress_display


class SimpleProgressTask:
    """
    Simple progress task for non-TTY environments.

    Mimics Rich Progress task interface with logging.
    """

    def __init__(self, description: str, total: Optional[int] = None):
        """Initialize simple progress task."""
        self.description = description
        self.total = total
        self.completed = 0
        self._printed_start = False

    def update(self, description: Optional[str] = None, advance: int = 0):
        """Update task progress."""
        if description:
            self.description = description

        if advance > 0:
            self.completed += advance

        # Print progress at 25%, 50%, 75%, 100%
        if self.total:
            percentage = (self.completed / self.total) * 100
            if percentage >= 25 and not hasattr(self, "_25"):
                print(f"  {self.description}: 25% complete", file=sys.stderr, flush=True)
                self._25 = True
            elif percentage >= 50 and not hasattr(self, "_50"):
                print(f"  {self.description}: 50% complete", file=sys.stderr, flush=True)
                self._50 = True
            elif percentage >= 75 and not hasattr(self, "_75"):
                print(f"  {self.description}: 75% complete", file=sys.stderr, flush=True)
                self._75 = True
            elif percentage >= 100 and not hasattr(self, "_100"):
                print(f"  {self.description}: 100% complete", file=sys.stderr, flush=True)
                self._100 = True


class SimpleProgress:
    """
    Simple progress display for non-TTY environments.

    Mimics Rich Progress interface with logging to stderr.
    """

    def __init__(self, *args, **kwargs):
        """Initialize simple progress."""
        self.tasks = []

    def __enter__(self):
        """Context manager entry."""
        return self

    def __exit__(self, *args):
        """Context manager exit."""
        pass

    def add_task(self, description: str, total: Optional[int] = None, **kwargs) -> int:
        """
        Add task and print start message.

        Args:
            description: Task description
            total: Total steps (optional)

        Returns:
            Task ID (index in tasks list)
        """
        task = SimpleProgressTask(description, total)
        self.tasks.append(task)
        print(f"▶ {description}", file=sys.stderr, flush=True)
        return len(self.tasks) - 1

    def update(self, task_id: int, **kwargs):
        """
        Update task progress.

        Args:
            task_id: Task ID to update
            **kwargs: Update parameters (description, advance, etc.)
        """
        if task_id < len(self.tasks):
            self.tasks[task_id].update(**kwargs)


def create_progress(*args, console: Optional[Console] = None, **kwargs):
    """
    Create appropriate progress display based on environment.

    Args:
        *args: Arguments for Rich Progress
        console: Rich console (for TTY mode)
        **kwargs: Keyword arguments for Rich Progress

    Returns:
        Rich Progress or SimpleProgress based on environment
    """
    if should_use_progress_display():
        # TTY mode: use Rich Progress
        return RichProgress(*args, console=console, **kwargs)
    else:
        # Container mode: use simple logging
        return SimpleProgress(*args, **kwargs)
