"""
nterm Help Dialog — QWebEngineView-based help viewer.

Displays help.html in a styled QDialog with context-sensitive
fragment navigation. Launched from Help menu or F1.

Integration:
    1. Copy help.html to nterm/static/help/help.html
    2. Copy help_content.json to nterm/static/help/help_content.json
    3. Import and wire in nterm_desktop.py (see docstring below)

Wiring into nterm_desktop.py:
    from nterm.help_dialog import HelpDialog

    # In _build_menu(), in the Help section:
    help_action = QAction("&Help Topics", self)
    help_action.setShortcut(QKeySequence("F1"))
    help_action.triggered.connect(self._show_help)
    help_menu.addAction(help_action)

    # Add method to NtermDesktop class:
    def _show_help(self):
        section = self._detect_help_context()
        if hasattr(self, '_help_dialog') and self._help_dialog is not None:
            try:
                self._help_dialog.navigate_to(section)
                self._help_dialog.raise_()
                self._help_dialog.activateWindow()
                return
            except RuntimeError:
                pass
        self._help_dialog = HelpDialog(
            server_url=self.server_url,
            fragment=section,
            parent=self,
        )
        self._help_dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
        self._help_dialog.destroyed.connect(
            lambda: setattr(self, '_help_dialog', None)
        )
        self._help_dialog.show()

    def _detect_help_context(self) -> str:
        # Template tester is open
        if (hasattr(self, '_template_tester_window')
                and self._template_tester_window is not None):
            try:
                if self._template_tester_window.isActiveWindow():
                    return 'tfsm-tester'
            except RuntimeError:
                pass
        # Telemetry pane has focus
        sizes = self.splitter.sizes()
        if sizes[1] > 100 and self.telemetry_tabs.count() > 0:
            focused = QApplication.focusWidget()
            if focused and self.telemetry_container.isAncestorOf(focused):
                return 'wirlwind'
        return 'nterm'
"""

import logging
from PyQt6.QtWidgets import QDialog, QVBoxLayout
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import Qt, QUrl

logger = logging.getLogger("nterm.help")


class HelpDialog(QDialog):
    """
    Help viewer dialog.

    Hosts help.html in a QWebEngineView, matching the nterm dark theme.
    Non-modal so the user can reference help while working.

    Args:
        server_url: Base URL of the nterm FastAPI server (for static file serving)
        fragment: Initial topic/section ID to navigate to (e.g. 'vault', 'wirlwind')
        parent: Parent QWidget
    """

    def __init__(
        self,
        server_url: str,
        fragment: str = "",
        parent=None,
    ):
        super().__init__(parent)
        self.server_url = server_url.rstrip("/")
        self._fragment = fragment

        self.setWindowTitle("nterm Help")
        self.setMinimumSize(900, 640)
        self.resize(1060, 740)
        self.setModal(False)

        # ── Layout ───────────────────────────────────────────
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        self._view = QWebEngineView()
        layout.addWidget(self._view)

        # ── Load ─────────────────────────────────────────────
        url = f"{self.server_url}/static/help/help.html"
        if fragment:
            url += f"#{fragment}"

        self._view.setUrl(QUrl(url))
        logger.info(f"Help dialog opened: {url}")

    def navigate_to(self, fragment: str):
        """
        Navigate to a specific help topic by fragment ID.

        Can be called on an already-open dialog to jump to a new topic.
        """
        if not fragment:
            return
        js = f"navigateTo('{fragment}');"
        self._view.page().runJavaScript(js)
        logger.debug(f"Help navigated to: {fragment}")