#!/usr/bin/env python3
"""
BidBrain Phase 1 build runner.

What it does, in order:
  1. Set up the local database on this machine.
  2. Load the cars you entered by hand in data/cars.json.
  3. Run the buying brain over them (the bans, the hard gate, the pricing rule).
  4. Save the run to the database.
  5. Write the cockpit page to cockpit.html.
  6. Print a short summary to the screen.

It never scrapes anything and it never places a bid. It recommends only.

Run it with:   python3 build.py
Then open:     cockpit.html
"""

import os
import sys

from bidbrain import db, loader, render
from bidbrain.pricing import assess_all, pounds

OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cockpit.html")

# Show the held back and rejected cars on the page?
# True  while you are checking the brain, so you can see what it cut and why.
# False for the final daily build, so the page shows only cars worth bidding on.
# The held and rejected cars are still saved to the database either way.
SHOW_EXCLUDED = True


def main():
    print("BidBrain Phase 1\n")

    # 1. Database.
    db.init_db()
    print(f"Database ready at {db.DB_PATH}")

    # 2. Load hand entered cars, failing loudly on bad data.
    try:
        cars = loader.load_cars()
    except loader.CarDataError as e:
        print("\nStopping. The car data could not be read.\n")
        print(f"  {e}\n")
        sys.exit(1)
    print(f"Loaded {len(cars)} cars from {loader.CARS_PATH}")

    db.replace_cars(cars)

    # 3. Run the brain.
    shortlist, held, rejected = assess_all(cars)

    # 4. Save the run.
    db.save_assessments(shortlist + held + rejected)

    # 5. Write the page.
    page = render.render_page(shortlist, held, rejected, show_excluded=SHOW_EXCLUDED)
    with open(OUT_PATH, "w", encoding="utf-8") as f:
        f.write(page)

    # 6. Summary.
    print(f"\nShortlist, cheapest reserve first, {len(shortlist)} cars:")
    for a in shortlist:
        c = a.car
        line = f"  {c.reserve and pounds(c.reserve):>8}  max bid {pounds(a.pricing.max_bid):>8}  {c.year} {c.make} {c.model} {c.derivative}".rstrip()
        if c.actually_paid is not None:
            line += f"   (you paid {pounds(c.actually_paid)})"
        print(line)

    if held:
        print(f"\nHeld back, {len(held)} cars, valuation could not be read:")
        for a in held:
            print(f"  {a.car.year} {a.car.make} {a.car.model} {a.car.derivative}".rstrip())

    if rejected:
        print(f"\nRejected, {len(rejected)} cars:")
        for a in rejected:
            reason = a.reasons[0] if a.reasons else ""
            print(f"  {a.car.year} {a.car.make} {a.car.model} {a.car.derivative}".rstrip() + f"   {reason}")

    print(f"\nCockpit page written to {OUT_PATH}")
    print("Open it in your browser to check the prices.\n")


if __name__ == "__main__":
    main()
