"""
Lets CompMatch (bid_suggest.py, BidBrain's own suggested bid engine) learn
from another dealership's real data too, not just this Mac's own (Mark
2026-08-25: "we are both happy for CompMatch to learn from both our data
can you wire this in", Right Drive and Steven's Really Easy Car Credit,
each running their own separate BidBrain install on their own Mac with
their own local database). Chosen mechanism, Mark's own pick: the shared
private GitHub repo both dealerships already use to collaborate on the
code, see shared_comps/README.md.

Only the fields CompMatch itself compares are ever exported: name (make
and model, free text), amount, retail, mileage, year, transmission,
engine, grade, the exact same shape db.bid_comps_full() already returns.
Never a registration, a dealer name beyond the file's own name, a price
breakdown, a margin, or anything else about either business. See golden
rule 6, keep purchase and margin data local; this is a deliberate,
narrow, both-sides-agreed exception for comp data only, not a general
data sharing channel.
"""

import json
import os
import re

from . import db

SHARED_COMPS_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "shared_comps")

# date (the comp's own sale date, YYYY-MM-DD, nothing about either
# business) joined the safe set 2026-08-25: bid_suggest now windows out
# comps too old to be evidence of today's market, and a shared comp with
# no date is excluded from that window rather than assumed recent (hold
# back rather than guess), so an export without dates would silently
# contribute nothing. Re-export after updating to a version with this
# field so the other dealership's CompMatch can actually use your comps.
_SAFE_FIELDS = ("name", "amount", "retail", "mileage", "year", "transmission", "engine", "grade", "date")


def dealer_key(name: str) -> str:
    """A filesystem and git safe slug from a dealer name ("Right Drive" ->
    "right_drive"), so shared_comps/<key>.json never depends on exact
    capitalisation or spacing matching between two different Macs."""
    slug = re.sub(r"[^a-z0-9]+", "_", (name or "").strip().lower()).strip("_")
    return slug or "dealer"


def export_comps(dealer_name: str, out_dir: str = SHARED_COMPS_DIR, db_path: str = db.DB_PATH):
    """Writes this dealership's own comps (whatever db.bid_comps_full()
    already returns, stripped to only the fields CompMatch uses) to
    shared_comps/<dealer_key>.json. Returns (path, comp count) — the count
    is free here and is what the Run modal's own CompMatch card reports
    (2026-08-31); it used to return the path alone, so the one real number
    this function knows was computed and thrown away. Raises if
    dealer_name is blank, a nameless file would be meaningless to merge
    and a sign DEALER_NAME was never set in dealer_config.py."""
    if not dealer_name or not dealer_name.strip():
        raise ValueError(
            "No dealer name given. Set DEALER_NAME in your own dealer_config.py "
            "before sharing comp data.")
    os.makedirs(out_dir, exist_ok=True)
    comps = [{f: c.get(f) for f in _SAFE_FIELDS} for c in db.bid_comps_full(path=db_path)
              if c.get("name") and c.get("amount") is not None]
    out_path = os.path.join(out_dir, f"{dealer_key(dealer_name)}.json")
    with open(out_path, "w", encoding="utf-8") as f:
        json.dump({"dealer": dealer_name, "comps": comps}, f, indent=1)
    return out_path, len(comps)


def load_shared_comps(exclude_dealer: str = None, comps_dir: str = SHARED_COMPS_DIR) -> list:
    """Every OTHER dealership's own exported comps found under
    shared_comps/, combined into one flat list in the same shape
    db.bid_comps_full() returns, ready to merge with this Mac's own local
    comps. exclude_dealer (this Mac's own dealer name) is skipped, this
    Mac's own live database already covers its own comps more freshly
    than a snapshot file ever could. A missing or empty folder returns
    an empty list, never an error, a fresh checkout with nothing shared
    yet works exactly as it always did."""
    own_key = dealer_key(exclude_dealer) if exclude_dealer else None
    out = []
    if not os.path.isdir(comps_dir):
        return out
    for fname in sorted(os.listdir(comps_dir)):
        if not fname.endswith(".json"):
            continue
        if own_key and fname == f"{own_key}.json":
            continue
        try:
            with open(os.path.join(comps_dir, fname), encoding="utf-8") as f:
                data = json.load(f)
        except (OSError, ValueError):
            continue
        out.extend(data.get("comps", []))
    return out
