# console_ui.py (Reverted to simple version)
import sys
from rich.progress import (
    Progress,
    BarColumn,
    TextColumn,
    TimeElapsedColumn,
)
from rich.console import Console
from threading import Lock
import time
import logging
from logger import app_logger  # Use app_logger for internal messages


class ConsoleUI:
    """Manages console output using rich.progress for overall status."""

    def __init__(self, total_items: int):
        self.total_items = total_items
        self._lock = Lock()
        self._current_ok = 0
        self._current_failed = 0

        console_target = sys.stdout if sys.stdout.isatty() else sys.stderr
        self._console = (
            Console(file=console_target) if console_target.isatty() else None
        )

        if self._console:
            self._progress = Progress(
                TextColumn("[bold blue]{task.description}", justify="left"),
                BarColumn(bar_width=None),
                TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
                TextColumn("[bold green]{task.fields[ok_count]} OK"),
                TextColumn("[bold red]{task.fields[fail_count]} Failed"),
                TextColumn("[cyan]{task.completed}/{task.total} Items"),
                TimeElapsedColumn(),
                console=self._console,
                transient=False,  # Keep visible after finishing
                refresh_per_second=5,
            )
            # Single task for overall progress
            self.main_task_id = self._progress.add_task(
                "Overall Progress",
                total=self.total_items,
                start=False,  # Don't start automatically
                ok_count=0,
                fail_count=0,
            )
            app_logger.debug("Console UI initialized with Rich Progress.")
        else:
            self._progress = None
            self.main_task_id = None
            app_logger.warning(
                "Console output is not a TTY. Rich Progress UI disabled."
            )

    def start(self):
        """Starts the progress display."""
        if self._progress:
            try:
                self._progress.start()
                # Start the main task only after starting the progress bar
                if self.main_task_id is not None:
                    self._progress.start_task(self.main_task_id)
                app_logger.debug("Rich Progress bar started.")
            except Exception as e:
                app_logger.error(f"Error starting Rich Progress: {e}", exc_info=True)
                self._progress = None
                self.main_task_id = None

    def stop(self):
        """Stops the progress display."""
        if self._progress:
            try:
                # Ensure final update before stopping
                self.update_progress(self._current_ok, self._current_failed)
                self._progress.stop()
                app_logger.debug("Rich Progress bar stopped.")
            except Exception as e:
                app_logger.error(f"Error stopping Rich Progress: {e}", exc_info=True)

    def update_progress(self, completed: int, failed: int):
        """Updates the overall progress bar."""
        if not self._progress or self.main_task_id is None:
            return

        if self.main_task_id not in self._progress.task_ids:
            return  # Check task exists

        try:
            with self._lock:
                self._current_ok = completed
                self._current_failed = failed
                processed = completed + failed
                # Ensure completed count doesn't exceed total for the bar display
                completed_for_bar = min(processed, self.total_items)

                self._progress.update(
                    self.main_task_id,
                    completed=completed_for_bar,
                    ok_count=completed,  # Use custom fields for accurate counts
                    fail_count=failed,
                )
        except Exception as e:
            app_logger.error(f"Error updating overall UI status: {e}", exc_info=False)

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()


# Example Usage (for testing - kept simple)
if __name__ == "__main__":
    import random
    import configparser
    import logger  # Import logger to test interaction

    dummy_config = configparser.ConfigParser()
    dummy_config["Misc"] = {"log_level": "INFO", "debug_mode": "false"}
    logger.setup_logging(dummy_config)

    TOTAL = 50
    ui = ConsoleUI(TOTAL)

    print(
        "Starting UI test (Simple Progress bar should appear below if console is TTY)..."
    )
    with ui:
        completed = 0
        failed = 0
        for i in range(TOTAL):
            time.sleep(random.uniform(0.05, 0.15))
            is_success = random.random() > 0.15
            if is_success:
                completed += 1
            else:
                failed += 1
            ui.update_progress(completed, failed)
    print("UI test finished.")
