#!/usr/bin/env python3
"""
BidBrain lost bids capture.

Reads every real auction bid on and lost (Motorway's own Bids & offers >
Didn't win screen for now, Mark 2026-08-24: "the original vision for BB
was to use ai to understand from our own data our best sellers... to make
educated bids... we could also use data that we bid on that didnt win").
Purchases alone only ever show what we actually paid; a lost auction's own
real "Sold for" price is the other half of that picture, how much it
actually would have taken to win, ready for a future suggested bid feature.

A lost outcome never changes once recorded, so this is a plain read and
store, no status updates, no email, unlike purchases_run.py.

  python3 lost_bids_run.py                read the first 2 pages (daily top up)
  python3 lost_bids_run.py --backfill     read the whole history (all pages)

Reads screens only. Never bids, never acts on the platforms.
"""

import sys

from playwright.sync_api import sync_playwright

from bidbrain import db, runs
from bidbrain.readers import motorway


# Progress and the terminal record both come from bidbrain.runs, the one
# way every script reports (2026-09-02, the runs audit).
_progress = runs.progress


def main():
    runs.begin("lost_bids")
    db.init_db()
    backfill = "--backfill" in sys.argv
    # A daily sync reads only the new cars at the top of the list and stops
    # at the first one already on file (Steven 2026-09-09: "all you need to
    # look for is new cars that have been added to didnt win"); the page
    # cap is only a safety net for a day with more losses than that. A
    # backfill reads the whole real history (931 rows, about 38 pages, seen
    # live 2026-08-24), stopping itself once a page comes back empty.
    known = None if backfill else db.lost_bid_refs("Motorway")
    max_pages = 60 if backfill else 4

    _progress("reading", "Reading Motorway's Didn't win screen for new cars...")
    with sync_playwright() as p:
        rows = motorway.read_didnt_win(
            p, max_pages=max_pages, known=known,
            on_page=lambda n, so_far: _progress("reading", f"Didn't win page {n}, {so_far} new so far..."))
    print(f"Motorway: {len(rows)} lost bids read")

    new = db.record_lost_bids(rows)
    if backfill:
        summary = f"{len(rows)} read, {len(new)} new"
    elif new:
        summary = f"{len(new)} new car{'s' if len(new) != 1 else ''}"
    else:
        summary = "No new cars, every car on the list is already on file."
    print(summary)
    runs.finish("lost_bids", True, summary)


if __name__ == "__main__":
    runs.guard("lost_bids", main)
