"""Real-browser adapter using Playwright (sync API).

    pip install playwright
    playwright install chromium

Element indexes come from `observe()`: we tag each interactive element in the live DOM
with a data attribute, so index N always refers to the same element the model saw.
This adapter is not exercised by the unit tests (they use a fake browser).
"""

from __future__ import annotations

from .dom import Element, Observation

TAG_SCRIPT = r"""
() => {
  const sel = 'a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=link]';
  const out = [];
  let i = 0;
  document.querySelectorAll('[data-agent-index]').forEach(e => e.removeAttribute('data-agent-index'));
  for (const el of document.querySelectorAll(sel)) {
    const r = el.getBoundingClientRect();
    const st = getComputedStyle(el);
    if (r.width === 0 || r.height === 0 || st.visibility === 'hidden' || st.display === 'none' || el.disabled) continue;
    i += 1;
    el.setAttribute('data-agent-index', String(i));
    const attrs = {};
    for (const a of ['type','name','id','href','placeholder','aria-label','value','autocomplete','role']) {
      const v = el.getAttribute(a); if (v !== null) attrs[a] = a === 'value' && el.type === 'password' ? '' : v;
    }
    let label = '';
    if (el.labels && el.labels.length) label = el.labels[0].innerText.trim();
    out.push({index: i, tag: el.tagName.toLowerCase(), attrs, text: (el.innerText || '').trim().slice(0, 120), label});
  }
  return out;
}
"""


class PlaywrightBrowser:
    def __init__(self, headless: bool = True, start_url: str = "about:blank"):
        from playwright.sync_api import sync_playwright  # imported lazily

        self._pw = sync_playwright().start()
        self._browser = self._pw.chromium.launch(headless=headless)
        # A fresh context: no cookies or logins from your personal profile.
        self._context = self._browser.new_context()
        self.page = self._context.new_page()
        self.page.set_default_timeout(10_000)
        if start_url != "about:blank":
            self.page.goto(start_url)

    def _el(self, index: int):
        return self.page.locator(f'[data-agent-index="{index}"]')

    def observe(self) -> Observation:
        self.page.wait_for_load_state("domcontentloaded")
        raw = self.page.evaluate(TAG_SCRIPT)
        elements = [Element(r["index"], r["tag"], r["attrs"], r["text"], r["label"]) for r in raw]
        text = self.page.inner_text("body") if self.page.url != "about:blank" else ""
        return Observation(self.page.url, self.page.title(), elements, text)

    def goto(self, url: str) -> None:
        self.page.goto(url, wait_until="domcontentloaded")

    def click(self, index: int) -> None:
        self._el(index).click()
        self.page.wait_for_load_state("domcontentloaded")

    def type(self, index: int, text: str) -> None:
        self._el(index).fill(text)

    def select(self, index: int, option: str) -> None:
        self._el(index).select_option(label=option)

    def scroll(self, direction: str) -> None:
        self.page.mouse.wheel(0, 800 if direction == "down" else -800)

    def back(self) -> None:
        self.page.go_back()

    def wait(self, seconds: float) -> None:
        self.page.wait_for_timeout(seconds * 1000)

    def close(self) -> None:
        self._context.close()
        self._browser.close()
        self._pw.stop()
