'''Helper for MarkdownViwer, so we don't try to relative chase down http links'''

from pathlib import Path
import webbrowser

from textual.widgets import MarkdownViewer, Markdown

from opencos import util

def get_opencos_docs_fpath(filename: str):
    '''Tries to get the docs/filename from the package or however eda was called'''

    opencos_dir = Path(util.__file__).parent # util.py location
    docs_dir = None
    # Try to get it from site-packages dir, which should have docs/ alongside
    # commands/ and tools/
    if (opencos_dir / 'docs' / 'README.md').is_file():
        docs_dir = opencos_dir / 'docs'
    elif (opencos_dir / '..' / 'docs' / 'README.md').is_file():
        docs_dir = opencos_dir / '..' / 'docs'

    if not docs_dir or not docs_dir.is_dir():
        return None

    docs_fpath = docs_dir / filename
    if not docs_fpath.is_file():
        return None

    return docs_fpath


class CustomHelpViewer(MarkdownViewer):
    '''Note you must call the constructor with open_links=False'''

    current_file_path = get_opencos_docs_fpath('README.md')

    BINDINGS = [
        ("ctrl+left", "back", "Back"),
        ("ctrl+right", "forward", "Forward"),
    ]

    def __init__(self, *args, **kwargs):

        kwargs['open_links'] = False
        kwargs['show_table_of_contents'] = False

        super().__init__(*args, **kwargs)
        self.history_pages = []
        self.history_idx = -1

    async def action_back(self) -> None:
        """Step back one in history"""
        if self.history_idx > 0:
            self.history_idx -= 1
            path = self.history_pages[self.history_idx]
            await super().go(str(path))
            self.current_file_path = path

    async def action_forward(self) -> None:
        """Step forward one in history"""
        if self.history_idx < len(self.history_pages) - 1:
            self.history_idx += 1
            path = self.history_pages[self.history_idx]
            await super().go(str(path))
            self.current_file_path = path

    async def go(self, location: str) -> None:
        """Override load to capture the path before calling super().go()"""
        if not location:
            return

        if not location.startswith('#'):
            target = Path(location).resolve()
            if target.parent.is_dir():
                # If someone gave me a full directory, maybe make sure that exists?
                self.current_file_path = target

                # Update history, only keep 50 items
                self.history_pages.append(target)
                if len(self.history_pages) > 50:
                    self.history_pages.pop(0)
                self.history_idx = len(self.history_pages) - 1

        await super().go(location)

    async def on_markdown_link_clicked(self, event: Markdown.LinkClicked) -> None:
        '''Handle the on-click for links'''
        event.stop()
        event.prevent_default()
        href = event.href

        if href.startswith(("http://", "https://")):
            # Use your OS's default browser to open the URL
            webbrowser.open(href)
            return

        # Get the directory of the file currently in the viewer
        # Assuming you loaded the initial file via a Path object
        target_path = (self.current_file_path.parent / href).resolve()
        go_str = str(target_path)

        if target_path.is_file():
            pass
        else:
            try_path = get_opencos_docs_fpath(str(href))
            try_path2 = get_opencos_docs_fpath(str(target_path))
            # Check the parent dir for existence, so I don't have to split
            # '#' on heading links, if that's what the link had:
            if try_path.parent.is_dir():
                go_str = str(try_path)
            elif try_path2.parent.is_dir():
                go_str = str(try_path2)

        # Feel lucky:
        try:
            await self.go(go_str)
        except: # pylint: disable=bare-except
            pass
