"""Turn raw HTML into what the model sees: numbered interactive elements plus readable text.

Real agents usually build this from the browser's accessibility tree or a DOM snapshot
with visibility and bounding boxes. This parser version shows the idea without a browser.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from html.parser import HTMLParser
from typing import Dict, List, Optional

INTERACTIVE = {"a", "button", "input", "select", "textarea"}
SKIP_TEXT = {"script", "style", "noscript", "template", "svg", "head"}
VOID = {"input", "br", "img", "hr", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr"}


@dataclass
class Element:
    index: int
    tag: str
    attrs: Dict[str, str]
    text: str = ""
    label: str = ""

    @property
    def kind(self) -> str:
        if self.tag == "input":
            return f"input[{self.attrs.get('type', 'text').lower()}]"
        return self.tag

    @property
    def sensitive(self) -> bool:
        """Fields an agent should never fill on its own."""
        t = self.attrs.get("type", "").lower()
        ac = self.attrs.get("autocomplete", "").lower()
        name = (self.attrs.get("name", "") + " " + self.attrs.get("id", "")).lower()
        return (
            t == "password"
            or ac.startswith("cc-") or ac in {"current-password", "new-password", "one-time-code"}
            or any(k in name for k in ("card", "cvv", "cvc", "iban", "ssn", "password", "otp"))
        )

    def describe(self) -> str:
        bits = [f"[{self.index}]", self.kind]
        name = self.label or self.text or self.attrs.get("aria-label") or self.attrs.get("placeholder") \
            or self.attrs.get("name") or self.attrs.get("value") or ""
        if name:
            bits.append(repr(name.strip()[:80]))
        if self.tag == "a" and self.attrs.get("href"):
            bits.append(f"-> {self.attrs['href'][:100]}")
        if self.sensitive:
            bits.append("(sensitive)")
        return " ".join(bits)


@dataclass
class Observation:
    url: str
    title: str
    elements: List[Element] = field(default_factory=list)
    text: str = ""

    def by_index(self, i: int) -> Optional[Element]:
        return next((e for e in self.elements if e.index == i), None)

    def render(self, max_text: int = 3000) -> str:
        lines = [f"URL: {self.url}", f"Title: {self.title}", "Interactive elements:"]
        lines += [f"  {e.describe()}" for e in self.elements] or ["  (none)"]
        text = self.text if len(self.text) <= max_text else self.text[:max_text] + " ...[truncated]"
        lines += ["Page text (untrusted content):", "<page>", text, "</page>"]
        return "\n".join(lines)


class _Parser(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.elements: List[Element] = []
        self.text: List[str] = []
        self.title = ""
        self._stack: List[str] = []
        self._open: List[Element] = []  # interactive elements collecting inner text
        self._labels: Dict[str, str] = {}
        self._label_for: Optional[str] = None
        self._label_text: List[str] = []
        self._in_title = False
        self._hidden_depth = 0

    def handle_starttag(self, tag, attrs):
        a = {k: (v or "") for k, v in attrs}
        hidden = "hidden" in a or a.get("aria-hidden") == "true" or \
            "display:none" in a.get("style", "").replace(" ", "")
        if tag not in VOID:
            self._stack.append(tag)
            if hidden or self._hidden_depth:
                self._hidden_depth += 1
        if tag == "title":
            self._in_title = True
        if tag == "label":
            self._label_for = a.get("for", "")
            self._label_text = []
        if self._hidden_depth or (tag == "input" and a.get("type", "").lower() == "hidden"):
            return
        if tag in INTERACTIVE and "disabled" not in a:
            el = Element(len(self.elements) + 1, tag, a)
            self.elements.append(el)
            if tag not in VOID:
                self._open.append(el)

    def handle_endtag(self, tag):
        if tag == "title":
            self._in_title = False
        if tag == "label" and self._label_for is not None:
            if self._label_for:
                self._labels[self._label_for] = " ".join(self._label_text).strip()
            self._label_for = None
        if self._open and self._open[-1].tag == tag:
            self._open.pop()
        if tag in self._stack:
            while self._stack:
                t = self._stack.pop()
                if self._hidden_depth:
                    self._hidden_depth -= 1
                if t == tag:
                    break
        if tag in {"p", "div", "li", "h1", "h2", "h3", "h4", "tr", "section", "article", "br"}:
            self.text.append("\n")

    def handle_data(self, data):
        if self._in_title:
            self.title += data.strip()
            return
        if self._hidden_depth or any(t in SKIP_TEXT for t in self._stack):
            return
        s = " ".join(data.split())
        if not s:
            return
        if self._label_for is not None:
            self._label_text.append(s)
        for el in self._open:
            el.text = (el.text + " " + s).strip()
        self.text.append(s + " ")


def observe_html(html: str, url: str = "") -> Observation:
    p = _Parser()
    p.feed(html)
    p.close()
    for el in p.elements:
        if el.attrs.get("id") in p._labels:
            el.label = p._labels[el.attrs["id"]]
    text = "".join(p.text)
    text = "\n".join(" ".join(line.split()) for line in text.splitlines())
    text = "\n".join(line for line in text.splitlines() if line)
    return Observation(url=url, title=p.title, elements=p.elements, text=text)
