"""Static, fail-closed BeamNG ABS lowering.

The adapter recognizes one fingerprinted BeamNG wheel-core shape. It never
loads or executes source Lua and does not attempt general controller translation.
"""
from __future__ import annotations

import hashlib
import json
import math
import os
import re
import stat
from pathlib import Path
from typing import Any, Callable

from beamng_jbeam import (BRAKE_AXLE_PATTERN, decode_jbeam_table,
                          pressure_wheel_options, selected_part_axle)


ADAPTER_SCHEMA = "helix.beamng-controller-adapter/1"
SOURCE_RECEIPT_SCHEMA = "helix.beamng-controller-source-receipt/1"
RECEIPT_PATH = Path(__file__).resolve().parent.parent / "controller-adapters" / "beamng-0.39.4-abs.json"
RECEIPT_SHA256 = "a5221e536221a7fbba16bd14f33490904138ae1fad52f6abaa5ae41057e1e317"
SHA256 = re.compile(r"^[a-f0-9]{64}$")
MAX_RECEIPT_BYTES = 64 * 1024


def _record(value: Any) -> bool:
    return isinstance(value, dict)


def _positive_number(value: Any) -> bool:
    return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0


def _static_pressure_wheel_options(body: dict[str, Any]) -> tuple[dict[str, Any], str | None]:
    """Admit only the state-only pressureWheels shape reviewed by adapter v1.

    A data row makes option scope wheel-specific. Until the adapter can prove
    the fully merged wheel stream, flattening those scopes would be unsafe.
    """
    section = body.get("pressureWheels")
    options = pressure_wheel_options(body)
    if not isinstance(section, list) or not section or not isinstance(section[0], list):
        return options, "pressureWheels is not the reviewed table shape"
    if any(isinstance(row, list) for row in section[1:]):
        return options, "pressureWheels contains wheel-scoped data rows"
    if any(not isinstance(row, dict) for row in section[1:]):
        return options, "pressureWheels contains an unknown row shape"
    return options, None


def _nested_keys(value: Any) -> set[str]:
    keys: set[str] = set()
    stack = [value]
    while stack:
        current = stack.pop()
        if isinstance(current, dict):
            keys.update(key for key in current if isinstance(key, str))
            stack.extend(current.values())
        elif isinstance(current, list):
            stack.extend(current)
    return keys


def _nested_string_values(value: Any, key: str) -> set[str]:
    values: set[str] = set()
    stack = [value]
    while stack:
        current = stack.pop()
        if isinstance(current, dict):
            if isinstance(current.get(key), str):
                values.add(current[key])
            stack.extend(current.values())
        elif isinstance(current, list):
            stack.extend(current)
    return values


def _read_receipt_bytes(path: Path) -> bytes:
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
    descriptor = os.open(path, flags)
    try:
        info = os.fstat(descriptor)
        if not stat.S_ISREG(info.st_mode) or info.st_size <= 0 or info.st_size > MAX_RECEIPT_BYTES:
            raise ValueError("BeamNG ABS controller receipt is not a bounded regular file")
        chunks: list[bytes] = []
        remaining = info.st_size
        while remaining:
            chunk = os.read(descriptor, min(remaining, 64 * 1024))
            if not chunk:
                break
            chunks.append(chunk)
            remaining -= len(chunk)
        payload = b"".join(chunks)
        after = os.fstat(descriptor)
        if len(payload) != info.st_size or (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) != (
                info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns):
            raise ValueError("BeamNG ABS controller receipt changed while reading")
        return payload
    finally:
        os.close(descriptor)


def load_abs_source_receipt(path: Path = RECEIPT_PATH) -> dict[str, Any]:
    payload = _read_receipt_bytes(path)
    if hashlib.sha256(payload).hexdigest() != RECEIPT_SHA256:
        raise ValueError("BeamNG ABS controller source receipt does not match adapter v1")
    receipt = json.loads(payload)
    adapter = receipt.get("adapter")
    beamng = receipt.get("beamng")
    module = receipt.get("sourceModule")
    shape = receipt.get("sourceShape")
    projection = receipt.get("portableProjection")
    extraction = receipt.get("extraction")
    valid = (
        receipt.get("schemaVersion") == SOURCE_RECEIPT_SCHEMA
        and adapter == {"id": "beamng.wheels.realistic-abs", "version": 1}
        and beamng == {"appid": "284160", "steamBuildId": "24617469", "version": "0.39.4.0"}
        and _record(module) and module.get("path") == "lua/vehicle/wheels.lua"
        and SHA256.fullmatch(str(module.get("sha256", ""))) is not None
        and isinstance(module.get("sizeBytes"), int) and 0 < module["sizeBytes"] <= 256 * 1024
        and _record(shape) and shape.get("id") == "beamng.wheels.realistic-abs/1"
        and shape.get("activationField") == "enableABS"
        and shape.get("allowedActivationControllerFiles") == []
        and shape.get("allowedAbsControllerFiles") == []
        and shape.get("controllerFileClassifier") == "case-insensitive-name-contains-abs"
        and shape.get("targetSlipField") == "absSlipRatioTarget"
        and _positive_number(shape.get("targetSlipDefault")) and shape["targetSlipDefault"] < 1
        and shape.get("frequencyField") == "absHz" and _positive_number(shape.get("frequencyDefaultHz"))
        and shape.get("forbiddenControllerFiles") == ["absLegacy"]
        and shape.get("pressureWheelsScope") == "state-only-no-data-rows"
        and _record(projection) and projection.get("status") == "approximate"
        and projection.get("targetSlipRule") == "uniform-selected-absSlipRatioTarget-or-source-default"
        and _positive_number(projection.get("releaseRate"))
        and _positive_number(projection.get("applyRate"))
        and _positive_number(projection.get("minSpeed"))
        and isinstance(projection.get("note"), str) and bool(projection["note"])
        and _record(extraction) and extraction.get("rawLuaRetained") is False
        and extraction.get("filesRead") == 2
    )
    if not valid:
        raise ValueError("BeamNG ABS adapter source receipt is incompatible or incomplete")
    return receipt


def _unsupported(base: dict[str, Any], reason: str, activations: list[dict[str, Any]],
                 axle_targets: dict[str, Any], provenance: list[dict[str, Any]]) -> tuple[None, dict[str, Any], bool]:
    semantics = {**base, "status": "unsupported", "reason": reason,
                 "activationCandidates": activations, "axleTargets": axle_targets}
    provenance.append({
        "target": "simulation.land.abs",
        "source": "selected JBeam ABS controller shape",
        "disposition": "unsupported",
        "detail": reason,
    })
    return None, semantics, False


def lower_selected_abs(selected: list[tuple[str, str, dict[str, Any], Path]],
                       configuration_file: str, configuration_sha256: str,
                       source_receipt_path: Path | None,
                       label_source: Callable[[Path], str],
                       provenance: list[dict[str, Any]]) -> tuple[dict[str, float] | None, dict[str, Any], bool]:
    receipt = load_abs_source_receipt()
    shape = receipt["sourceShape"]
    projection = receipt["portableProjection"]
    module = receipt["sourceModule"]
    base = {
        "schemaVersion": ADAPTER_SCHEMA,
        "adapterId": receipt["adapter"]["id"],
        "adapterVersion": receipt["adapter"]["version"],
        "beamng": {"version": receipt["beamng"]["version"],
                    "steamBuildId": receipt["beamng"]["steamBuildId"]},
        "sourceModule": module,
        "sourceReceiptSha256": RECEIPT_SHA256,
        "sourceShapeId": shape["id"],
        "selectedConfiguration": {"file": configuration_file, "sha256": configuration_sha256},
    }
    if source_receipt_path is None:
        return _unsupported(base, "No verified BeamNG ABS controller source receipt was supplied.", [], {}, provenance)
    try:
        load_abs_source_receipt(source_receipt_path)
    except (OSError, ValueError, json.JSONDecodeError) as error:
        return _unsupported(base, f"BeamNG ABS controller source receipt was not admitted: {error}.", [], {}, provenance)
    activation_field = shape["activationField"]
    activations: list[dict[str, Any]] = []
    parameter_occurrences: list[dict[str, Any]] = []
    controller_files: set[str] = set()
    controller_shape_errors: list[str] = []
    abs_shape_errors: list[str] = []
    activation_controller_files: set[str] = set()
    activation_shape_errors: list[str] = []
    axle_parts: dict[str, list[tuple[str, str, dict[str, Any], Path, dict[str, Any], str | None]]] = {
        "front": [], "rear": []}
    for slot_name, part_name, body, path in selected:
        options, shape_error = _static_pressure_wheel_options(body)
        section = body.get("pressureWheels")
        has_activation_occurrence = False
        occurrence_fields = (activation_field, "enableABSactuator",
                             shape["targetSlipField"], shape["frequencyField"])
        field_set = set(occurrence_fields)
        if not isinstance(section, list):
            hidden_fields = sorted(_nested_keys(section).intersection(field_set))
            if hidden_fields:
                abs_shape_errors.append(
                    f"{part_name}: malformed pressureWheels contains {', '.join(hidden_fields)}")
        elif section and isinstance(section[0], list):
            header_fields = sorted(value for value in section[0]
                                   if isinstance(value, str) and value.rstrip(":") in field_set)
            if header_fields:
                abs_shape_errors.append(
                    f"{part_name}: pressureWheels header declares {', '.join(header_fields)}")
        if isinstance(section, list):
            for row_index, row in enumerate(section[1:], start=1):
                scoped_options = ([row] if isinstance(row, dict) else
                                  [value for value in row if isinstance(value, dict)]
                                  if isinstance(row, list) else [])
                for scoped in scoped_options:
                    for field in occurrence_fields:
                        if field not in scoped:
                            continue
                        occurrence = {
                            "slotType": slot_name,
                            "partName": part_name,
                            "path": str(path),
                            "source": f"{label_source(path)}#{part_name}.pressureWheels[{row_index}].{field}",
                            "field": field,
                            "value": scoped[field],
                        }
                        if field in (activation_field, "enableABSactuator"):
                            has_activation_occurrence = True
                            activations.append({key: value for key, value in occurrence.items()
                                                if key != "path"})
                        else:
                            parameter_occurrences.append(occurrence)
        controller_section = body.get("controller")
        raw_controller_files = _nested_string_values(controller_section, "fileName")
        try:
            decoded_controllers = decode_jbeam_table(controller_section)
        except ValueError as error:
            decoded_controllers = []
            controller_shape_errors.append(f"{part_name}: {error}")
        if controller_section is not None and (
                not isinstance(controller_section, list)
                or not controller_section
                or not isinstance(controller_section[0], list)):
            controller_shape_errors.append(f"{part_name}: controller is not the reviewed table shape")
        elif raw_controller_files and not decoded_controllers:
            controller_shape_errors.append(f"{part_name}: controller fileName occurs outside a data row")
        part_controller_files = {
            row["fileName"] for row in decoded_controllers if isinstance(row.get("fileName"), str)
        }
        part_controller_files.update(raw_controller_files)
        controller_files.update(part_controller_files)
        if has_activation_occurrence:
            if shape_error is not None:
                activation_shape_errors.append(f"{part_name}: {shape_error}")
            if body.get("controller") is not None and not part_controller_files:
                activation_shape_errors.append(f"{part_name}: controller table is not allowlisted")
            activation_controller_files.update(part_controller_files)
        axle = selected_part_axle(BRAKE_AXLE_PATTERN, slot_name, part_name, body)
        if axle is not None and ("brakeTorque" in options or "parkingTorque" in options):
            axle_parts[axle].append((slot_name, part_name, body, path, options, shape_error))

    forbidden = sorted(controller_files.intersection(shape["forbiddenControllerFiles"]))
    if forbidden:
        return _unsupported(base, f"Selected ABS controller files are not allowlisted: {', '.join(forbidden)}.",
                            activations, {}, provenance)
    if controller_shape_errors:
        return _unsupported(base, "Selected controller tables contain unknown shapes: "
                            + "; ".join(sorted(controller_shape_errors)), activations, {}, provenance)
    unknown_abs_controllers = sorted(
        filename for filename in controller_files
        if "abs" in filename.casefold()
        and filename not in shape["forbiddenControllerFiles"]
        and filename not in shape["allowedAbsControllerFiles"]
    )
    if unknown_abs_controllers:
        return _unsupported(base, "Selected ABS-named controller files are not allowlisted: "
                            + ", ".join(unknown_abs_controllers), activations, {}, provenance)
    if abs_shape_errors:
        return _unsupported(base, "Selected ABS fields use unreviewed pressureWheels shapes: "
                            + "; ".join(sorted(abs_shape_errors)), activations, {}, provenance)
    unknown_activation_controllers = sorted(
        activation_controller_files.difference(shape["allowedActivationControllerFiles"]))
    if unknown_activation_controllers:
        return _unsupported(
            base,
            f"Selected ABS activation part declares controller files not allowlisted: {', '.join(unknown_activation_controllers)}.",
            activations,
            {},
            provenance,
        )
    if activation_shape_errors:
        return _unsupported(base, "Selected ABS activation is wheel-scoped or malformed: "
                            + "; ".join(sorted(activation_shape_errors)), activations, {}, provenance)

    brake_owner_keys = {
        (part_name, str(path))
        for rows in axle_parts.values()
        for _, part_name, _, path, _, _ in rows
    }
    misplaced_parameters = sorted(
        row["source"] for row in parameter_occurrences
        if (row["partName"], row["path"]) not in brake_owner_keys
    )
    if misplaced_parameters:
        return _unsupported(
            base,
            "Selected ABS parameters occur outside selected brake owners: " + ", ".join(misplaced_parameters),
            activations,
            {},
            provenance,
        )
    duplicate_parameters = sorted(
        f"{part_name}.{field}"
        for part_name, path, field in {
            (row["partName"], row["path"], row["field"]) for row in parameter_occurrences
        }
        if sum(1 for row in parameter_occurrences
               if row["partName"] == part_name and row["path"] == path and row["field"] == field) > 1
    )
    if duplicate_parameters:
        return _unsupported(
            base,
            "Selected ABS parameters contain duplicate override shapes: " + ", ".join(duplicate_parameters),
            activations,
            {},
            provenance,
        )
    enabled = [row for row in activations if row["field"] == activation_field and row["value"] is True]
    other_shapes = [row for row in activations if row not in enabled]
    if len(enabled) != 1 or other_shapes:
        reason = (f"Expected exactly one selected {activation_field}=true activation and no alternate ABS actuator shape; "
                  f"found {len(enabled)} allowlisted and {len(other_shapes)} alternate candidates.")
        return _unsupported(base, reason, activations, {}, provenance)

    axle_targets: dict[str, Any] = {}
    for axle in ("front", "rear"):
        rows = axle_parts[axle]
        if len(rows) != 1:
            return _unsupported(base, f"Expected one selected {axle} brake owner for ABS; found {len(rows)}.",
                                activations, axle_targets, provenance)
        _, part_name, _, path, options, shape_error = rows[0]
        if shape_error is not None:
            return _unsupported(base, f"Selected {axle} ABS options are not statically scoped: {shape_error}.",
                                activations, axle_targets, provenance)
        target_raw = options.get(shape["targetSlipField"])
        target = shape["targetSlipDefault"] if target_raw is None else target_raw
        frequency_raw = options.get(shape["frequencyField"])
        frequency = shape["frequencyDefaultHz"] if frequency_raw is None else frequency_raw
        if not _positive_number(target) or target >= 1:
            return _unsupported(base, f"Selected {axle} ABS target slip is not a portable finite ratio.",
                                activations, axle_targets, provenance)
        if not _positive_number(frequency) or frequency != shape["frequencyDefaultHz"]:
            return _unsupported(base, f"Selected {axle} ABS frequency is not the allowlisted {shape['frequencyDefaultHz']:g} Hz shape.",
                                activations, axle_targets, provenance)
        axle_targets[axle] = {
            "partName": part_name,
            "source": f"{label_source(path)}#{part_name}.pressureWheels",
            "raw": target_raw,
            "value": float(target),
            "status": "source-default" if target_raw is None else "source-literal",
            "frequencyHz": float(frequency),
        }

    unique_targets = {row["value"] for row in axle_targets.values()}
    if len(unique_targets) != 1:
        values = ", ".join(f"{axle}={row['value']:g}" for axle, row in axle_targets.items())
        return _unsupported(base, f"HELIX AbsSpec has one targetSlip but selected BeamNG axle targets differ ({values}).",
                            activations, axle_targets, provenance)

    target_slip = next(iter(unique_targets))
    runtime = {
        "targetSlip": target_slip,
        "releaseRate": float(projection["releaseRate"]),
        "applyRate": float(projection["applyRate"]),
        "minSpeed": float(projection["minSpeed"]),
    }
    activation = enabled[0]
    semantics = {
        **base,
        "status": "adapted",
        "parity": projection["status"],
        "activation": activation,
        "activationCandidates": activations,
        "axleTargets": axle_targets,
        "runtime": runtime,
        "limitations": [projection["note"]],
    }
    target_sources = ", ".join(axle_targets[axle]["source"] for axle in ("front", "rear"))
    provenance.extend([
        {
            "target": "simulation.land.abs.targetSlip",
            "source": target_sources,
            "disposition": "derived",
            "detail": f"Selected front/rear targets agree at {target_slip:g}; source default {shape['targetSlipDefault']:g} is fingerprinted when absent.",
        },
        {
            "target": "simulation.land.abs.modulationRates",
            "source": f"{receipt['adapter']['id']}@{receipt['adapter']['version']}",
            "disposition": "defaulted",
            "detail": projection["note"],
        },
    ])
    return runtime, semantics, True
