"""
LE Capital (LE Stocktrak Pro) stock funding reader.

LE Capital is the stocking loan (floorplan) facility funding Right Drive's
stock, a genuinely different kind of relationship to every other platform in
this project: it is not somewhere cars are bought, it is who lent the money
to buy them. Added 2026-08-24 (Mark: "LE captial is the source of truth as
this is the funding platform, i need DK funding to match the LE portal").

Two screens matter, both plain rendered lists (Angular, PrimeNG), read the
same way this project already reads Motorway's or Carwow's own screens, by
inner text, not an API:

- Current Stock (stocktrak.lecapital.co.uk/stock/current-stock): every car
  still actively funded right now. Each entry's own date group heading is
  the date the loan started (proven live: HG17NRF grouped under "21 Aug '26"
  read "3 days funded" on 24 Aug, 21 plus 3 is 24, exact).
- Stock History (stocktrak.lecapital.co.uk/stock/stock-history): every loan
  that has since been repaid, each entry's own group heading is the date it
  was SETTLED (the first group explicitly labelled "(Settled Date)" on the
  live page, every group after it the same field, just not relabelled).
  Each entry also carries its own "Funded: DD/MM/YYYY" text directly, the
  real date the loan started, so unlike Current Stock this needs no date
  group inference for that one.

A real export button exists on Current Stock, but it turned out to build its
CSV client side from data already on the page (a real blob: URL was seen,
not a server request), so it gives nothing text parsing does not already
have; not used here.

Never guesses: an entry with a reg that does not look like a real UK plate
is skipped rather than mangled into a wrong record.
"""

import re

# Current style (AB12CDE) or the older prefix/personalised style (S33DFB,
# genuinely on this real account, S 33 DFB, one letter not two before the
# digits), the same two shapes clickdealer.py's own VRM regex already
# covers for the same reason.
_REG_RE = re.compile(r"^([A-Z]{2}\d{2}[A-Z]{3}|[A-Z]\d{1,3}[A-Z]{3})$")
_DATE_GROUP_RE = re.compile(
    r"^(\d{1,2} \w{3} '\d{2})(?: \(Settled Date\))?$")
_FUNDING_REF_RE = re.compile(r"^\d{5}-\d{6}-\d{4}$")
_DAYS_FUNDED_RE = re.compile(r"^(\d+) days funded$")
_FUNDED_ON_RE = re.compile(
    r"^Funded: (\d{2})/(\d{2})/(\d{4}) - \d+ days funded$")
_AMOUNT_RE = re.compile(r"^£([\d,]+\.\d{2})$")

_MONTHS = {
    "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06",
    "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12",
}


def _parse_group_date(text):
    """"21 Aug '26" -> "2026-08-21". Assumes 20xx, true for every real date
    on this account so far and for the foreseeable life of this project."""
    day, mon, yr = text.split()
    return f"20{yr.lstrip(chr(39))}-{_MONTHS[mon]}-{int(day):02d}"


def _parse_current_stock_text(text):
    """Pure function over already read body text, so the parsing itself can
    be tested without a live page. Each real entry: an optional date group
    heading, the reg, the VIN, a status word (Sold, In Stock, etc, ignored,
    DealerKit's own stock status is what this project actually gates on
    elsewhere), "View", the description, the funding reference, "N days
    funded", the funded amount. Returns a list of dicts: reg, vin,
    plan_starts_at ("YYYY-MM-DD"), funded_value, funding_ref."""
    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
    records = []
    current_date = None
    i = 0
    while i < len(lines):
        m = _DATE_GROUP_RE.match(lines[i])
        if m:
            current_date = _parse_group_date(m.group(1))
            i += 1
            continue
        if _REG_RE.match(lines[i]) and current_date:
            reg = lines[i]
            vin = lines[i + 1] if i + 1 < len(lines) else None
            j = i + 2
            # Skip the status word(s) up to and including "View".
            while j < len(lines) and lines[j] != "View":
                j += 1
            j += 1  # past "View"
            description = lines[j] if j < len(lines) else None
            j += 1
            funding_ref = lines[j] if j < len(lines) and _FUNDING_REF_RE.match(lines[j]) else None
            j += 1
            days_m = _DAYS_FUNDED_RE.match(lines[j]) if j < len(lines) else None
            j += 1
            amt_m = _AMOUNT_RE.match(lines[j]) if j < len(lines) else None
            if vin and funding_ref and days_m and amt_m:
                records.append({
                    "reg": reg,
                    "vin": vin,
                    "description": description,
                    "funding_ref": funding_ref,
                    "plan_starts_at": current_date,
                    "funded_value": float(amt_m.group(1).replace(",", "")),
                })
                i = j + 1
                continue
        i += 1
    return records


def _parse_stock_history_text(text):
    """Same shape as _parse_current_stock_text, but for Stock History:
    the date group is the SETTLED date, and each entry's own "Funded:
    DD/MM/YYYY" line gives the real loan start date directly, no group
    based inference needed for that one. Returns a list of dicts: reg,
    vin, plan_starts_at, settled_on, funded_value, funding_ref."""
    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
    records = []
    current_settled = None
    i = 0
    while i < len(lines):
        m = _DATE_GROUP_RE.match(lines[i])
        if m:
            current_settled = _parse_group_date(m.group(1))
            i += 1
            continue
        if _REG_RE.match(lines[i]) and current_settled:
            reg = lines[i]
            vin = lines[i + 1] if i + 1 < len(lines) else None
            j = i + 2
            if j < len(lines) and lines[j] == "View":
                j += 1
            description = lines[j] if j < len(lines) else None
            j += 1
            funding_ref = lines[j] if j < len(lines) and _FUNDING_REF_RE.match(lines[j]) else None
            j += 1
            funded_m = _FUNDED_ON_RE.match(lines[j]) if j < len(lines) else None
            j += 1
            amt_m = _AMOUNT_RE.match(lines[j]) if j < len(lines) else None
            if vin and funding_ref and funded_m and amt_m:
                d, mo, y = funded_m.group(1), funded_m.group(2), funded_m.group(3)
                records.append({
                    "reg": reg,
                    "vin": vin,
                    "description": description,
                    "funding_ref": funding_ref,
                    "plan_starts_at": f"{y}-{mo}-{d}",
                    "settled_on": current_settled,
                    "funded_value": float(amt_m.group(1).replace(",", "")),
                })
                i = j + 1
                continue
        i += 1
    return records


def read_current_stock(page):
    """Every car LE Capital is still actively funding right now. Reads the
    already logged in page's own body text (page must already be on
    stock/current-stock, this reader does not navigate itself, the same
    convention as this project's other list readers)."""
    return _parse_current_stock_text(page.inner_text("body"))


def read_stock_history(page):
    """Every loan LE Capital has recorded as settled (repaid). Reads the
    already logged in page's own body text (page must already be on
    stock/stock-history)."""
    return _parse_stock_history_text(page.inner_text("body"))
