#!/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 char_utils


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

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

    def run(self):
        self.env["screen"]["oldCursorReview"] = self.env["screen"][
            "newCursorReview"
        ]
        if not self.env["screen"]["newCursorReview"]:
            self.env["screen"]["newCursorReview"] = self.env["screen"][
                "new_cursor"
            ].copy()

        # Check if we're in table mode for bounded navigation
        if self.env["runtime"]["TableManager"].is_table_mode():
            table_info = self.env["runtime"]["TableManager"].get_current_table_cell_info()
            if table_info:
                cursor_pos = self.env["screen"]["newCursorReview"]
                line_text = self.env["runtime"]["ScreenManager"].get_line_text(
                    cursor_pos["y"]
                )
                if line_text:
                    column_start = self.env["runtime"]["TableManager"].get_column_start_position(
                        line_text, table_info["column_index"]
                    )
                    
                    # Check if we're already at the start of the cell
                    if cursor_pos["x"] <= column_start:
                        # At cell boundary - announce start and don't move
                        char_utils.present_char_for_review(
                            self.env,
                            (
                                table_info["cell_content"][0] 
                                if table_info["cell_content"] else ""
                            ),
                            interrupt=True,
                            announce_capital=True,
                            flush=False,
                        )
                        self.env["runtime"]["OutputManager"].present_text(
                            _("start of cell"), 
                            interrupt=False, 
                            sound_icon="StartOfLine"
                        )
                        return
                    
                    # Move within cell bounds
                    cell_content = table_info["cell_content"]
                    relative_pos = cursor_pos["x"] - column_start
                    if relative_pos > 0:
                        new_relative_pos = relative_pos - 1
                        self.env["screen"]["newCursorReview"]["x"] = (
                            column_start + new_relative_pos
                        )
                        
                        # Get character at new position
                        if new_relative_pos < len(cell_content):
                            prev_char = cell_content[new_relative_pos]
                        else:
                            prev_char = ""
                        
                        char_utils.present_char_for_review(
                            self.env,
                            prev_char,
                            interrupt=True,
                            announce_capital=True,
                            flush=False,
                        )
                        return

        # Regular navigation for non-table mode
        (
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            prev_char,
            end_of_screen,
            line_break,
        ) = char_utils.get_prev_char(
            self.env["screen"]["newCursorReview"]["x"],
            self.env["screen"]["newCursorReview"]["y"],
            self.env["screen"]["new_content_text"],
        )

        char_utils.present_char_for_review(
            self.env,
            prev_char,
            interrupt=True,
            announce_capital=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=True,
                    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"
                )
        # is has attribute it enabled?
        if self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "general", "hasattributes"
        ):
            cursor_pos = self.env["screen"]["newCursorReview"]

            if not self.env["runtime"]["AttributeManager"].has_attributes(
                cursor_pos
            ):
                return
            self.env["runtime"]["OutputManager"].present_text(
                "has attribute", sound_icon="HasAttributes", interrupt=False
            )

    def set_callback(self, callback):
        pass
