#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

from fenrirscreenreader.core.i18n import _
from fenrirscreenreader.utils import word_utils
from fenrirscreenreader.core import debug


class command:
    def __init__(self):
        pass

    def initialize(self, environment):
        self.env = environment

    def shutdown(self):
        pass

    def get_description(self):
        return _("moves review focus to the previous word ")

    def run(self):
        # Check if we're in table mode FIRST - before any word navigation
        is_table_mode = self.env["runtime"]["TableManager"].is_table_mode()
        self.env["runtime"]["DebugManager"].write_debug_out(
            f"review_prev_word: is_table_mode={is_table_mode}",
            debug.DebugLevel.INFO
        )
        if is_table_mode:
            table_info = (
                self.env["runtime"]["TableManager"].move_to_prev_column()
            )
            if table_info and table_info.get("at_start"):
                # Stay on current cell at beginning of line
                current_info = table_info["current_info"]
                if current_info:
                    output_text = (
                        f"{current_info['cell_content']} {current_info['column_header']}"
                    )
                    self.env["runtime"]["OutputManager"].present_text(
                        output_text, interrupt=True, flush=False
                    )
                    # Play start of line sound
                    self.env["runtime"]["OutputManager"].present_text(
                        _("start of line"), 
                        interrupt=False, 
                        sound_icon="StartOfLine"
                    )
            elif table_info:
                # Normal column navigation - announce cell content with column info
                output_text = (
                    f"{table_info['cell_content']} {table_info['column_header']}"
                )
                self.env["runtime"]["OutputManager"].present_text(
                    output_text, interrupt=True, flush=False
                )
            else:
                # No table info available, but still in table mode
                self.env["runtime"]["OutputManager"].present_text(
                    _("no table data"), interrupt=True, flush=False
                )
            return  # ALWAYS return in table mode to prevent regular word navigation

        # Regular word navigation (only when NOT in table mode)
        self.env["runtime"][
            "CursorManager"
        ].enter_review_mode_curr_text_cursor()

        (
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            prev_word,
            end_of_screen,
            line_break,
        ) = word_utils.get_prev_word(
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            self.env["screen"]["new_content_text"],
        )
        
        # Regular word announcement
        if prev_word.isspace():
            self.env["runtime"]["OutputManager"].present_text(
                _("blank"), interrupt=True, flush=False
            )
        else:
            self.env["runtime"]["OutputManager"].present_text(
                prev_word, interrupt=True, flush=False
            )
        if end_of_screen:
            if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
                "review", "end_of_screen"
            ):
                self.env["runtime"]["OutputManager"].present_text(
                    _("end of screen"),
                    interrupt=False,
                    sound_icon="EndOfScreen",
                )
        if line_break:
            if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
                "review", "line_break"
            ):
                self.env["runtime"]["OutputManager"].present_text(
                    _("line break"), interrupt=False, sound_icon="EndOfLine"
                )

    def set_callback(self, callback):
        pass
