"""
Glass's valuation lookup.

Given a registration and mileage, BidBrain enters them on the Glass's home page,
runs the valuation, and reads back the Glass's Retail value, the figure the
buying brain uses. It deliberately reads Glass's Retail, not the live retail
price and not the trade price.

The value sits in an element with id avBasicRetailPrice and a data-price
attribute holding the plain integer, for example 9085.

If the value cannot be read with confidence, this returns None so the caller
holds the car back rather than pricing it on a guess. It never bids.
"""

from .. import browser

HOME = "https://uk.glass.co.uk/"


def lookup(playwright, reg, mileage, headless=True):
    """Return the Glass's Retail value as a whole number of pounds, or None if
    it could not be read with confidence."""
    if not reg or mileage is None:
        return None

    ctx = browser.open_reader_context(playwright, "glass", headless=headless)
    try:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto(HOME, wait_until="domcontentloaded", timeout=40000)

        # Guard against a logged out session, which would never reach a value.
        try:
            page.wait_for_selector("#plateNumberInput", timeout=15000)
        except Exception:
            raise RuntimeError(
                "Glass's did not show the valuation box. The login may have expired. "
                "Run: python3 login.py glass, then try again."
            )

        page.fill("#plateNumberInput", str(reg).replace(" ", ""))
        page.fill("#mileageInput", str(int(mileage)))

        # The Go button runs the valuation.
        for sel in ['button:has-text("Go")', 'text=Go']:
            try:
                page.click(sel, timeout=4000)
                break
            except Exception:
                continue

        # After Go we either land straight on a valuation result, or on an
        # identification page that lists the matched cars.
        page.wait_for_timeout(3500)
        url = page.url

        if "/identification" in url:
            rows = page.query_selector_all(".ag-center-cols-container .ag-row")
            if len(rows) == 0:
                return None
            if len(rows) > 1:
                # More than one match. Only safe to proceed if every row is the
                # same edition (the same car valued before). Otherwise hold back,
                # we never guess which engine or trim it is. Play safe.
                editions = set()
                for r in rows:
                    cell = r.query_selector('[col-id="edition"], [col-id="editionName"]')
                    editions.add((cell.inner_text().strip() if cell else r.inner_text()).lower())
                if len(editions) > 1:
                    return None
            rows[0].click()

        # Now wait for the valuation result page.
        try:
            page.wait_for_url("**/valuations/**", timeout=20000)
        except Exception:
            return None

        # Reveal the full price summary if it is collapsed.
        for sel in ['text=Show more', 'button:has-text("Show more")']:
            try:
                page.click(sel, timeout=3000)
                break
            except Exception:
                continue

        # Read the Glass's Retail value from its element.
        try:
            page.wait_for_selector("#avBasicRetailPrice", timeout=10000)
            data_price = page.get_attribute("#avBasicRetailPrice", "data-price")
        except Exception:
            return None

        if data_price and str(data_price).strip().isdigit():
            return int(str(data_price).strip())
        return None
    finally:
        ctx.close()
