"""
Cazana retail lookup (the platform is now branded Percayso).

Given a registration and mileage, BidBrain enters them on the Cazana trade home
page, runs the valuation, and reads back the headline Retail value, the figure
the buying brain uses. It deliberately reads the headline Retail, not the
franchise, independent or supermarket breakdowns and not the Trade value.

The page has no stable id, so the value is found by locating the Retail block,
which uniquely contains the words Retail franchise, and reading its amount.

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.
"""

import re
from .. import browser

HOME = "https://trade.percayso-vehicle-intelligence.co.uk/"

# Reads the headline Retail amount from the vehicle overview panel.
_EXTRACT_JS = """
() => {
  const spans = [...document.querySelectorAll('p span')]
    .filter(s => s.textContent.trim() === 'Retail');
  for (const span of spans) {
    const row = span.closest('.columns');
    if (!row) continue;
    if (!/Retail franchise/i.test(row.textContent)) continue;
    const valCol = row.querySelector('.has-text-right');
    const p = valCol && valCol.querySelector('p');
    if (p) return p.textContent.trim();
  }
  return null;
}
"""


def _to_int(text):
    if not text:
        return None
    m = re.search(r"[\d,]+", str(text))
    if not m:
        return None
    n = m.group(0).replace(",", "")
    return int(n) if n.isdigit() else None


def lookup(playwright, reg, mileage, headless=True):
    """Return the Cazana headline Retail value as whole 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, "cazana", headless=headless)
    try:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto(HOME, wait_until="domcontentloaded", timeout=40000)

        try:
            page.wait_for_selector('input[name="value"]', timeout=15000)
        except Exception:
            raise RuntimeError(
                "Cazana did not show the search box. The login may have expired. "
                "Run: python3 login.py cazana, then try again."
            )

        page.fill('input[name="value"]', str(reg).replace(" ", ""))
        page.fill('input[name="mileage"]', str(int(mileage)))
        # Submit the search. Enter in the VRM field runs it.
        page.press('input[name="value"]', "Enter")

        # Wait to land on a vehicle result.
        try:
            page.wait_for_url("**/companion/search/**", timeout=30000)
        except Exception:
            return None

        # Wait for the Retail value to render, then read it.
        try:
            page.wait_for_function(_EXTRACT_JS, timeout=15000)
        except Exception:
            return None

        value_text = page.evaluate(_EXTRACT_JS)
        return _to_int(value_text)
    finally:
        ctx.close()
