"""Derive an engine's cylinder count from what a BeamNG mod actually declares.

BeamNG has no first-class ``cylinders`` field, so the count is read from the places modders and
the base game put it, strongest first:

1. ``operator``    an explicit ``beamngEngine`` Bridge input (``{"cylinders": 6}``) the importer's
                   operator supplied after reading the mod. Wins because it is a deliberate
                   correction, and is fingerprinted into the reviewed plan like any input.
2. ``declared``    a numeric field on the selected engine: ``fundamentalFrequencyCylinderCount`` in
                   ``soundConfig`` / ``soundConfigExhaust`` (what the base game's own engines
                   carry), or ``cylinderCount`` / ``numberOfCylinders`` / ``firingOrder`` on
                   ``mainEngine`` or the sound config.
3. ``layout-name`` an engine-layout designator in the selected engine part's ``information.name``
                   ("1.6L F4 Engine", "3.5L V8 Engine", "2.0L I4 Turbo", "Flat-6", "Inline 6").
4. ``sound-name``  the same designator inside the engine's sound identifiers: ``starterSample`` /
                   ``shutOffSample*`` FMOD event names and ``sampleName`` (``box4_2006_eng``,
                   ``v8flat_1986_eng``, ``b4p_1995_...``, ``i6_...``).
5. ``defaulted``   4, only when none of the above exists. Callers must say so.

Several designators in one engine can disagree (a mod that copied a V8 template into a flat-six).
The strongest wins and every disagreeing lower-tier reading is returned in ``conflicts`` so the
caller can surface it instead of hiding it.
"""
from __future__ import annotations

import re
from typing import Any, Iterable

DEFAULT_CYLINDERS = 4
MIN_CYLINDERS, MAX_CYLINDERS = 1, 16

_COUNT_FIELDS = ("fundamentalFrequencyCylinderCount", "cylinderCount", "numberOfCylinders", "numCylinders", "cylinders")

# "V8", "I4", "F4", "H6", "W12", "B4", "L6" -- one layout letter, then the count, as a whole token.
_LETTER_LAYOUT = re.compile(r"(?<![A-Za-z0-9])([VvIiLlHhFfWwBb])[\s_-]?(\d{1,2})(?![0-9])")
# "flat-6", "flat six", "boxer 4", "inline-6", "straight six", "vee 8".
_WORD_NUMBER = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "eight": 8, "ten": 10, "twelve": 12}
_WORD_LAYOUT = re.compile(
    r"(?<![A-Za-z0-9])(?:flat|boxer|inline|straight|vee|rotary)[\s_-]?(\d{1,2}|" + "|".join(_WORD_NUMBER) + r")(?![A-Za-z0-9])",
    re.I)
# Sound identifiers: ``box4``, ``v8flat``, ``b4p``, ``i6`` after a separator; never inside a hash.
_SOUND_LAYOUT = re.compile(
    r"(?<![A-Za-z0-9])(?:box|flat|inline|inl|v|i|l|h|f|w|b)(\d{1,2})(?![0-9])", re.I)
_HEXISH = re.compile(r"^[0-9A-Fa-f]{16,}$")


# A layout letter + number is only trusted for counts real engines have; "V2" in a sample name is
# a version, "I7" is not an engine.
_LAYOUT_COUNTS = {1, 2, 3, 4, 5, 6, 8, 10, 12, 16}


def _valid(count: Any) -> bool:
    return isinstance(count, int) and not isinstance(count, bool) and MIN_CYLINDERS <= count <= MAX_CYLINDERS


def _whole_number(value: Any) -> int | None:
    if isinstance(value, bool):
        return None
    if isinstance(value, (int, float)) and float(value) == int(value) and _valid(int(value)):
        return int(value)
    return None


def layout_cylinders(text: str) -> int | None:
    """Cylinder count named by an engine-layout designator in free text, or None."""
    for match in _LETTER_LAYOUT.finditer(text):
        # "L" alone also means litres ("3.5L"); a digit directly before it is a displacement.
        if match.group(1) in "Ll" and match.start() > 0 and text[match.start() - 1].isdigit():
            continue
        count = int(match.group(2))
        if count in _LAYOUT_COUNTS:
            return count
    word = _WORD_LAYOUT.search(text)
    if word:
        raw = word.group(1).lower()
        count = _WORD_NUMBER.get(raw) if raw in _WORD_NUMBER else int(raw)
        if _valid(count):
            return count
    return None


def sound_identifier_cylinders(identifier: str) -> int | None:
    """Cylinder count named inside a sound sample / FMOD event identifier, or None."""
    if _HEXISH.match(identifier.strip()):
        return None  # an opaque content hash, not a name
    for segment in re.split(r"[>:/\\]", identifier):
        for match in re.finditer(_SOUND_LAYOUT, segment):
            count = int(match.group(1))
            if count in _LAYOUT_COUNTS and count > 2:  # "v2"/"b1" in a sample name is a version tag
                return count
    return None


def _engine_bodies(parts: Iterable[tuple[str, dict[str, Any]]]) -> list[tuple[str, dict[str, Any]]]:
    """Selected parts that define the engine itself (a ``mainEngine`` with a torque table)."""
    rows = []
    for name, body in parts:
        engine = body.get("mainEngine")
        if isinstance(engine, dict) and engine.get("torque") is not None:
            rows.append((name, body))
    return rows


def derive_cylinders(parts: Iterable[tuple[str, dict[str, Any]]], sound: dict[str, Any],
                     exhaust: dict[str, Any], override: dict[str, Any] | None = None) -> dict[str, Any]:
    """Return ``{"count", "state", "source", "detail", "conflicts"}`` for the selected engine.

    ``parts`` is ``[(partName, body), ...]`` for the selected closure; ``sound`` / ``exhaust`` are the
    merged ``soundConfig`` / ``soundConfigExhaust`` dicts the caller already built.
    """
    parts = list(parts)
    engines = _engine_bodies(parts)
    readings: list[tuple[str, int, str]] = []  # (state, count, where)

    if override is not None:
        count = _whole_number(override.get("cylinders"))
        if count is None:
            raise ValueError("beamngEngine input needs an integer 'cylinders' between "
                             f"{MIN_CYLINDERS} and {MAX_CYLINDERS}")
        reason = override.get("reason")
        return {"count": count, "state": "operator", "source": "beamngEngine input",
                "detail": f"Operator-declared cylinder count {count} (beamngEngine input)"
                          + (f": {reason}" if isinstance(reason, str) and reason.strip() else "."),
                "conflicts": []}

    # 2. numeric fields
    for where, config in (("soundConfig", sound), ("soundConfigExhaust", exhaust)):
        for key in _COUNT_FIELDS:
            count = _whole_number(config.get(key))
            if count is not None:
                readings.append(("declared", count, f"{where}.{key}"))
    for name, body in engines:
        main = body["mainEngine"]
        for key in _COUNT_FIELDS:
            count = _whole_number(main.get(key))
            if count is not None:
                readings.append(("declared", count, f"{name}.mainEngine.{key}"))
        order = main.get("firingOrder")
        if isinstance(order, list) and order and all(isinstance(v, int) and not isinstance(v, bool) for v in order) \
                and sorted(order) == list(range(1, len(order) + 1)) and _valid(len(order)):
            readings.append(("declared", len(order), f"{name}.mainEngine.firingOrder"))

    # 3. engine part's own name
    for name, body in engines:
        information = body.get("information")
        label = information.get("name") if isinstance(information, dict) else None
        if isinstance(label, str):
            count = layout_cylinders(label)
            if count is not None:
                readings.append(("layout-name", count, f"{name}.information.name \"{label}\""))

    # 4. sound identifiers
    identifiers: list[tuple[str, str]] = []
    for config, where in ((sound, "soundConfig"), (exhaust, "soundConfigExhaust")):
        if isinstance(config.get("sampleName"), str):
            identifiers.append((f"{where}.sampleName", config["sampleName"]))
    for name, body in engines:
        main = body["mainEngine"]
        for key in ("starterSample", "starterSampleExhaust", "shutOffSampleEngine", "shutOffSampleExhaust"):
            if isinstance(main.get(key), str):
                identifiers.append((f"{name}.mainEngine.{key}", main[key]))
    for where, identifier in identifiers:
        count = sound_identifier_cylinders(identifier)
        if count is not None:
            readings.append(("sound-name", count, f"{where} \"{identifier}\""))

    order_of = {"declared": 0, "layout-name": 1, "sound-name": 2}
    readings.sort(key=lambda row: order_of[row[0]])
    if not readings:
        checked = ("soundConfig.fundamentalFrequencyCylinderCount, mainEngine cylinder fields / firingOrder, "
                   "the engine part's information.name layout (V8, I6, F4, flat-6...), and the starter / shut-off / "
                   "sample sound names")
        return {"count": DEFAULT_CYLINDERS, "state": "defaulted", "source": "HELIX default",
                "detail": f"No cylinder count is declared by the selected engine (checked {checked}); "
                          f"defaulted to {DEFAULT_CYLINDERS}. Supply a beamngEngine input "
                          '({"cylinders": N}) with the real count.',
                "conflicts": []}
    state, count, where = readings[0]
    conflicts = [f"{w} says {c}" for s, c, w in readings[1:] if c != count]
    detail = f"{count} cylinders from {where} ({state})."
    if conflicts:
        detail += (" Lower-priority declarations disagree: " + "; ".join(conflicts)
                   + ". Supply a beamngEngine input if the winning reading is wrong.")
    return {"count": count, "state": state, "source": where, "detail": detail, "conflicts": conflicts}
