"""Make and model out of a free text car name (2026-09-14).

A bought car's row keeps the title the platform showed ("BMW 116D M Sport
Shadow Edition", "Mercedes A 180 D SE", "Kia c'eed 2 ISG CRDI") and,
until now, nothing else about what the car is. Dealer OS puts each due in
car under the live auction card of the same model, which needs the make
and model the card itself carries ("Bmw", "1 Series"). The sighting the
Mac already logged for the plate is the first choice (db._purchase_make_model);
this is the fallback for a car the Mac never listed, a hand added one for
instance. Same rules as bid_suggest.model_key and Dealer OS's own
know.nameToMakeModel, so all three land on the same model.

Pure: no database, no network, no clock.
"""
import re

_TWO_WORD_MAKES = ("mercedes benz", "mg motor uk", "mg motor", "land rover", "alfa romeo", "aston martin")
_YEAR_RE = re.compile(r"^(19|20)\d{2}$")
_BMW_BADGE_RE = re.compile(r"^(\d)\d{2}[a-z]{0,2}$", re.I)
_MERC_CLASS_RE = re.compile(r"^([a-z]{1,3})class$", re.I)
_MERC_BADGE_RE = re.compile(r"^([a-z]{1,3})\d{3}$", re.I)


def name_make_model(name):
    """("BMW", "1 Series") for "BMW 116D M Sport"; ("Mercedes", "A Class")
    for "Mercedes A180 AMG Line"; ("Kia", "Ceed 2 ISG CRDI") for "Kia c'eed
    2 ISG CRDI"; ("Land Rover", "Range Rover Evoque") for the whole name.
    A leading year is not the make. None when there is no model word."""
    words = [w for w in str(name or "").replace("'", "").split() if w]
    if words and _YEAR_RE.match(words[0]):
        words = words[1:]
    if not words:
        return None
    # Hyphens read as spaces for the rules only ("Mercedes-Benz", "A-Class");
    # the words themselves are kept as typed ("S-A" stays "S-A").
    lower = [w.lower().replace("-", " ") for w in words]
    make, rest = words[0], words[1:]
    for two in _TWO_WORD_MAKES:
        if lower[0] == two:
            break
        n = len(two.split())
        if " ".join(lower[:n]) == two:
            make, rest = " ".join(words[:n]), words[n:]
            break
    if not rest:
        return None
    mk = lower[0].split()[0]
    first = rest[0].replace("-", "")
    model = " ".join(rest)
    if mk == "bmw":
        m = _BMW_BADGE_RE.match(first)
        if m:
            model = f"{m.group(1)} Series"
    elif mk.startswith("mercedes"):
        m = _MERC_CLASS_RE.match(first) or _MERC_BADGE_RE.match(first)
        if m:
            model = f"{m.group(1).upper()} Class"
    elif mk == "vauxhall" and first.lower() == "insig":
        model = "Insignia"
    if model[:1].islower():
        model = model[:1].upper() + model[1:]  # "c'eed" read as "Ceed"
    return (make, model)
