#!/usr/bin/env python3
"""
Shares this dealership's own CompMatch data (bid_suggest.py's suggested
bid engine) with another dealership on the same BidBrain repo, so the
model learns from both (Mark 2026-08-25: "we are both happy for CompMatch
to learn from both our data", Right Drive and Steven's Really Easy Car
Credit). See shared_comps/README.md for exactly what is and is not
shared: only make/model, winning price, retail, mileage, age,
transmission, engine size and condition grade, never a registration, a
purchase price breakdown, a margin, or anything else about either
business.

  python3 share_comps.py --export
      Writes this Mac's own comps to shared_comps/<dealer_key>.json.
      Local only, never touches git.

  python3 share_comps.py --sync
      Pulls the latest shared_comps/ from the shared repo first (so this
      Mac sees the other dealership's newest data), exports this Mac's
      own fresh comps over it, then commits and pushes only if this
      Mac's own file actually changed. Only ever touches files under
      shared_comps/, nothing else in the working tree.

Requires DEALER_NAME set in your own dealer_config.py (never committed).
Read only against the platforms; the whole point of this script is what
it writes to the shared repo, not anything on Motorway, Carwow etc.
"""

import os
import subprocess
import sys

from bidbrain import comp_share, runs
from bidbrain import db
import dealer_config

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))


def _git(*args):
    return subprocess.run(["git", *args], cwd=PROJECT_ROOT, capture_output=True, text=True)


def export():
    # Same opted-out guard as sync(): without it, export_comps' own
    # ValueError on a blank name reached the crash wrapper's _record and
    # wrote the exact permanent, uncleareable CompMatch failure sync() was
    # fixed to avoid (the sweep's own verification round, 2026-09-01).
    name = getattr(dealer_config, "DEALER_NAME", "")
    if not name:
        print("No DEALER_NAME set in dealer_config.py, nothing to export. "
              "See shared_comps/README.md.")
        sys.exit(1)
    path, count = comp_share.export_comps(name)
    print(f"Exported {count} of {name}'s own comps to {path}")
    return path, count


# Progress and the durable record both come from bidbrain.runs (2026-09-02).
_progress = runs.progress


def _record(ok, summary):
    runs.finish("compmatch", ok, summary)


def sync():
    # Checked before anything is written anywhere: no DEALER_NAME means
    # this dealership has opted out of sharing, which is OFF, not broken.
    # Recording it as a failure turned the idle light permanently red with
    # nothing that could ever clear it (a success needs the very name that
    # is missing), found in the 2026-09-01 sweep.
    name = getattr(dealer_config, "DEALER_NAME", "")
    if not name:
        # Off, not broken: this dealership has not opted in to sharing.
        raise runs.RunSkipped("CompMatch sharing is not set up on this Mac (no DEALER_NAME "
                              "in dealer_config.py). Nothing shared.")
    _progress("reading", "Sharing CompMatch data...")

    print("Fetching the latest shared comp data...")
    r = _git("fetch", "origin", "main")
    if r.returncode != 0:
        print("git fetch failed:", r.stderr.strip())
        raise RuntimeError("git fetch failed")
    r = _git("checkout", "origin/main", "--", "shared_comps/")
    if r.returncode != 0:
        print("Could not update shared_comps/ from origin (it may not exist there "
              "yet), continuing with what's on disk:", r.stderr.strip())

    _, count = export()
    rel = f"shared_comps/{comp_share.dealer_key(name)}.json"
    r = _git("status", "--porcelain", "--", rel)
    if not r.stdout.strip():
        print(f"{rel} is already up to date, nothing to push.")
        _record(True, f"{count} comps, already up to date")
        return

    _git("add", rel)
    r = _git("commit", "-m", f"Update {name}'s own CompMatch data")
    if r.returncode != 0:
        print("git commit failed:", r.stderr.strip())
        raise RuntimeError("git commit failed")
    r = _git("push", "origin", "main")
    if r.returncode != 0:
        print("git push failed, someone else may have pushed since the fetch above, "
              "run this again to retry:", r.stderr.strip())
        raise RuntimeError("git push failed, someone else pushed first")
    print(f"Pushed {rel} to the shared repo.")
    _record(True, f"{count} comps shared")


def main():
    if "--sync" in sys.argv:
        sync()
    elif "--export" in sys.argv:
        export()
    else:
        print("Usage: python3 share_comps.py --export|--sync")
        sys.exit(1)


if __name__ == "__main__":
    if "--sync" in sys.argv:
        runs.guard("compmatch", sync)
    else:
        main()
