'''For opencos.tui, support viewing Text file artifacts with search bar'''
import os

from rich.syntax import Syntax
from rich.text import Text

from textual.screen import ModalScreen
from textual.widgets import Static, Label, Footer, Input
from textual.containers import VerticalScroll

class TextViewerModal(ModalScreen):
    '''Modal for text file viewing, with highlighting for text, json, yaml'''

    BINDINGS = [
        ("f", "toggle_search", "Find"),
        ("escape", "dismiss", "Close")
    ]

    def __init__(self, file_path: str):
        super().__init__()
        self.file_path = file_path
        self.raw_content = ''
        if os.path.exists(file_path):
            with open(file_path, "r", encoding='utf-8', errors='replace') as f:
                self.raw_content = f.read()
        self._set_lexer()


    def action_toggle_search(self) -> None:
        '''Method for handling 'f' (toggle_search)'''
        search_bar = self.query_one("#search-bar", Input)
        search_bar.toggle_class("hidden")
        if not search_bar.has_class("hidden"):
            search_bar.focus()

    def on_input_changed(self, event: Input.Changed) -> None:
        """Called as the user types in the search bar."""
        query = event.value
        content_widget = self.query_one("#file-content", Static)

        if not query:
            # Reset to plain text if search is empty
            content_widget.update(self.raw_content)
            return

        # Create a Rich Text object and highlight matches
        text = Text(self.raw_content)
        # style="reverse" makes the match pop; 'bold yellow' works too
        text.highlight_words([query], case_sensitive=False, style="black on yellow")
        content_widget.update(text)


    def _set_lexer(self) -> None:
        self.lexer = "text"
        if self.file_path.endswith(".json"):
            self.lexer = "json"
        elif self.file_path.endswith(".yaml"):
            self.lexer = "yaml"

    def compose(self):
        '''Textual Frame for text file'''
        yield Input(placeholder="Search...", id="search-bar", classes="hidden")
        with VerticalScroll(id="viewer-container"):
            try:
                yield Label(f"Viewing: {self.file_path}", id="viewer-header")
                yield Static(
                    Syntax(self.raw_content, self.lexer, theme="monokai", line_numbers=True),
                    id="file-content"
                )
            except Exception as e:
                yield Label(f"[red]Error reading file: {e}[/]")
        yield Footer()
