"""Interactive block – self-contained interactive HTML widget. Wraps :class:`deeptutor.agents.visualize.pipeline.VisualizePipeline` with ``render_mode="html"``. The payload carries an HTML document the frontend renders in an isolated iframe. The draft is normalized to a complete HTML document and checked by the deterministic local ``validate_visualization``. HTML has no repair pass (full single-file documents are too large for a useful targeted fix), so an unrenderable document raises ``GenerationFailure`` and lets the book engine retry — better than baking a placeholder page into the book. The one exception is a page that ran out of room — empty, or cut off before ````. A reasoning model can spend the whole output budget thinking, so that page is asked for once more with thinking turned off before failing. """ from __future__ import annotations from html.parser import HTMLParser import logging import re from typing import Any from deeptutor.services.keypool import primary_api_key from ..models import BlockType, SourceAnchor from ._prompts import get_book_prompt, load_book_prompts from .base import BlockContext, BlockGenerator, GenerationFailure logger = logging.getLogger(__name__) _HTML_START = re.compile(r"", re.IGNORECASE) class _DocumentParser(HTMLParser): """Find where the document really ends and check its scripts pair up. The parser treats script bodies as raw text, so an ```` inside a script string, a code fence in ``
`` or prose after the page cannot
    move the end of the document.
    """

    def __init__(self) -> None:
        super().__init__(convert_charrefs=False)
        self.end: tuple[int, int] | None = None
        self.open_scripts = 0
        self.extra_closes = 0

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if tag == "script" and self.end is None:
            self.open_scripts += 1

    def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        self.handle_starttag(tag, attrs)

    def handle_endtag(self, tag: str) -> None:
        if self.end is not None:
            return
        if tag == "html":
            self.end = self.getpos()
        elif tag == "script":
            if self.open_scripts:
                self.open_scripts -= 1
            else:
                self.extra_closes += 1


def _offset(text: str, position: tuple[int, int]) -> int:
    line, column = position
    offset = 0
    for _ in range(line - 1):
        offset = text.index("\n", offset) + 1
    return offset + column


class _OutOfRoom(GenerationFailure):
    """The model returned no page, or stopped before the page was finished.

    Both happen when a reasoning model spends the output budget on hidden
    thinking, so they are worth one more attempt with thinking turned off.
    """


def _budget_hint(max_tokens: int | None) -> str:
    budget = f"its {max_tokens}-token" if max_tokens else "its"
    return (
        f" It was retried with thinking turned off and still ran out of {budget} "
        "output budget: raise Max tokens in Settings → Capabilities → Visualize, "
        "or turn off thinking or lower the reasoning effort for this model in Settings."
    )


def _normalize_interactive_html(code: str) -> str:
    text = (code or "").strip()
    if not text:
        raise _OutOfRoom("interactive generation returned no code.")
    start = _HTML_START.search(text)
    if start is None:
        raise GenerationFailure(
            "interactive html is missing a document start ( or )."
        )
    text = text[start.start() :]

    parser = _DocumentParser()
    parser.feed(text)
    parser.close()
    if parser.end is None:
        if parser.open_scripts and _HTML_END.search(text) is not None:
            raise GenerationFailure("interactive html contains unpaired