from __future__ import annotations

import hashlib
import json
import os
import secrets
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Iterable

from liverylab_core import (
    official_car_resources,
    official_external_workflow,
    official_saved_car_state,
    official_variant_compatibility,
)
from liverylab_core.proto import ProtoField, build_fields, is_printable_utf8, parse_fields


PROJECT_SAVED_CAR_DIRNAME = "SavedCar"
SOURCE_LIVERYLAB_GENERATED = "liverylab_generated"
SOURCE_PACKAGE_EMBEDDED = "package_embedded"
SOURCE_REGISTERED_EXTERNAL = "registered_external"
DEPLOYABLE_SAVED_CAR_SOURCES = {
    SOURCE_LIVERYLAB_GENERATED,
    SOURCE_PACKAGE_EMBEDDED,
    SOURCE_REGISTERED_EXTERNAL,
}
KUNOS_DYNAMIC_GUID_PREFIX = "4"


def _sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _exact_fields(raw: bytes) -> list[ProtoField] | None:
    try:
        fields = parse_fields(raw)
        return fields if build_fields(fields) == raw else None
    except Exception:
        return None


def guid_parts(guid: Any) -> tuple[int, int]:
    normalized = official_saved_car_state.normalize_guid(guid)
    compact = normalized.replace("-", "")
    if len(compact) != 32:
        raise ValueError(f"Invalid GUID: {guid}")
    return int(compact[:16], 16), int(compact[16:], 16)


def new_pguid(reserved_guids: set[str] | None = None) -> str:
    reserved = reserved_guids if reserved_guids is not None else set()
    while True:
        raw = bytearray(secrets.token_bytes(16))
        raw[0] = (raw[0] & 0x0F) | 0x40
        compact = raw.hex()
        guid = f"{compact[:8]}-{compact[8:12]}-{compact[12:16]}-{compact[16:20]}-{compact[20:]}"
        if guid not in reserved:
            reserved.add(guid)
            return guid


def _next_guid(
    reserved: set[str],
    guid_factory: Callable[[], str] | None,
) -> str:
    if guid_factory is None:
        return new_pguid(reserved)
    for _attempt in range(1024):
        guid = official_saved_car_state.normalize_guid(guid_factory())
        if not guid:
            raise ValueError("GUID factory returned an invalid GUID.")
        if not guid.startswith(KUNOS_DYNAMIC_GUID_PREFIX):
            raise ValueError("Generated SavedCar GUIDs must use the observed Kunos dynamic GUID prefix 4.")
        if guid not in reserved:
            reserved.add(guid)
            return guid
    raise RuntimeError("GUID factory did not produce an unused GUID.")


def _replace_guid_pair(binary_fields: list[ProtoField], new_guid: str) -> bytes:
    high, low = guid_parts(new_guid)
    return build_fields([
        ProtoField(
            field.number,
            field.wire,
            high
            if field.wire == 0 and field.number == 1
            else low
            if field.wire == 0 and field.number == 2
            else field.value,
        )
        for field in binary_fields
    ])


def set_livery_linker(raw: bytes, livery_guid: Any) -> bytes:
    fields = _exact_fields(raw)
    if fields is None:
        raise ValueError("SavedCar livery linker target is not a valid protobuf message.")
    high, low = guid_parts(livery_guid)
    linker = build_fields([
        ProtoField(1, 0, high),
        ProtoField(2, 0, low),
    ])
    rebuilt: list[ProtoField] = []
    inserted = False
    for field in fields:
        if field.number == official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER:
            if not inserted:
                rebuilt.append(ProtoField(official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER, 2, linker))
                inserted = True
            continue
        if not inserted and field.number > official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER:
            rebuilt.append(ProtoField(official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER, 2, linker))
            inserted = True
        rebuilt.append(field)
    if not inserted:
        rebuilt.append(ProtoField(official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER, 2, linker))
    return build_fields(rebuilt)


def regenerate_instance_guids(
    raw: bytes,
    *,
    reserved_guids: Iterable[str] | None = None,
    guid_factory: Callable[[], str] | None = None,
    path: str = "",
) -> tuple[bytes, list[dict[str, str]]]:
    reserved = {
        guid
        for value in (reserved_guids or [])
        if (guid := official_saved_car_state.normalize_guid(value))
    }

    def patch_message(message: bytes, field_path: str) -> tuple[bytes, list[dict[str, str]]]:
        fields = _exact_fields(message)
        if fields is None:
            return message, []

        replacements: dict[int, bytes] = {}
        mappings: list[dict[str, str]] = []
        used_binary_fields: set[int] = set()

        for text_index, text_field in enumerate(fields):
            if text_field.number != 100 or text_field.wire != 2:
                continue
            text = is_printable_utf8(bytes(text_field.value)) or ""
            old_guid = official_saved_car_state.normalize_guid(text)
            if not old_guid:
                continue
            old_high, old_low = guid_parts(old_guid)
            binary_index = -1
            binary_fields: list[ProtoField] | None = None
            for candidate_index, candidate in enumerate(fields):
                if candidate_index in used_binary_fields or candidate.number != 101 or candidate.wire != 2:
                    continue
                nested = _exact_fields(bytes(candidate.value))
                if nested is None:
                    continue
                values = {
                    field.number: int(field.value)
                    for field in nested
                    if field.wire == 0 and field.number in (1, 2)
                }
                if values.get(1) == old_high and values.get(2) == old_low:
                    binary_index = candidate_index
                    binary_fields = nested
                    break
            if binary_index < 0 or binary_fields is None:
                raise ValueError(f"SavedCar GUID pair is incomplete at {field_path or '/'}: {old_guid}")

            new_guid = _next_guid(reserved, guid_factory)
            replacements[text_index] = new_guid.encode("utf-8")
            replacements[binary_index] = _replace_guid_pair(binary_fields, new_guid)
            used_binary_fields.add(binary_index)
            mappings.append({
                "path": field_path or "/",
                "oldGuid": old_guid,
                "newGuid": new_guid,
            })

        rebuilt: list[ProtoField] = []
        for index, field in enumerate(fields):
            if index in replacements:
                rebuilt.append(ProtoField(field.number, field.wire, replacements[index]))
                continue
            value = field.value
            if field.wire == 2:
                value, nested_mappings = patch_message(
                    bytes(field.value),
                    f"{field_path}/{field.number}[{index}]",
                )
                mappings.extend(nested_mappings)
            rebuilt.append(ProtoField(field.number, field.wire, value))
        return build_fields(rebuilt), mappings

    return patch_message(raw, path)


def normalize_instance_guids_for_comparison(raw: bytes, *, _depth: int = 0) -> bytes:
    fields = _exact_fields(raw)
    if fields is None:
        return raw
    normalized: list[ProtoField] = []
    for field in fields:
        if _depth == 0 and field.number == official_saved_car_state.LIVERY_LINKER_FIELD_NUMBER:
            continue
        value = field.value
        if field.wire == 2:
            raw_value = bytes(field.value)
            if field.number == 100 and official_saved_car_state.normalize_guid(is_printable_utf8(raw_value) or ""):
                value = b"00000000-0000-0000-0000-000000000000"
            elif field.number == 101:
                nested = _exact_fields(raw_value)
                if nested is not None:
                    value = build_fields([
                        ProtoField(
                            item.number,
                            item.wire,
                            0 if item.wire == 0 and item.number in (1, 2) else item.value,
                        )
                        for item in nested
                    ])
            else:
                value = normalize_instance_guids_for_comparison(raw_value, _depth=_depth + 1)
        normalized.append(ProtoField(field.number, field.wire, value))
    return build_fields(normalized)


def wrap_car_final_state(inner_data: bytes) -> bytes:
    consumable_payload = build_fields([ProtoField(1, 2, b"")])
    return build_fields([
        ProtoField(1, 2, consumable_payload),
        ProtoField(2, 2, inner_data),
    ])


def _content_relative_path(value: Any) -> Path:
    text = str(value or "").strip().replace("/", "\\").lstrip("\\")
    parts = [part for part in text.split("\\") if part]
    if not parts or parts[0].lower() != "content" or any(part in {".", ".."} for part in parts):
        raise ValueError(f"Official car final state must be a content-relative path: {value}")
    return Path(*parts)


def preserve_variant_sources(
    rows: list[dict[str, Any]],
    raw_root: str | Path,
    derived_root: str | Path,
    car_id: str,
    *,
    force: bool = False,
) -> dict[str, Any]:
    warnings: list[str] = []
    prepared: dict[tuple[str, str], Path] = {}
    used_names: dict[str, str] = {}
    source_root = Path(raw_root).resolve()
    derived = Path(derived_root).resolve()
    target_root = (derived / official_car_resources.SAVED_CAR_SOURCES_DIRNAME).resolve()

    for row in rows:
        if not isinstance(row, dict):
            continue
        relative_text = str(row.get("carFinalState") or "").strip()
        if not relative_text:
            warnings.append(f"Official vehicle variant {row.get('label') or row.get('id') or '-'} has no car final state source.")
            continue
        try:
            relative = _content_relative_path(relative_text)
        except Exception as exc:
            warnings.append(str(exc))
            continue
        source = (source_root / relative).resolve()
        try:
            source.relative_to(source_root)
        except ValueError:
            warnings.append(f"Official car final state resolves outside Raw resources: {relative_text}")
            continue
        if not source.exists() or not source.is_file():
            warnings.append(f"Official car final state source is missing: {relative_text}")
            continue
        try:
            source_data = source.read_bytes()
            source_sha256 = hashlib.sha256(source_data).hexdigest()
            inspection = official_saved_car_state.inspect_saved_car_bytes(source_data, source.name)
            if not inspection.get("valid") or inspection.get("wrapped"):
                raise ValueError("source is not a raw supported car final state")
            source_car = str(inspection.get("carModel") or "").strip().lower()
            if source_car != str(car_id or "").strip().lower():
                raise ValueError(f"source targets {source_car or '-'}, expected {car_id}")

            cache_key = (str(source).lower(), source_sha256)
            target = prepared.get(cache_key)
            if target is None:
                target_name = source.name
                previous_sha = used_names.get(target_name.lower())
                if previous_sha and previous_sha != source_sha256:
                    target_name = f"{source.stem}_{source_sha256[:12]}{source.suffix}"
                used_names[target_name.lower()] = source_sha256
                target = (target_root / target_name).resolve()
                target.relative_to(target_root)
                target.parent.mkdir(parents=True, exist_ok=True)
                target_matches = False
                if target.exists() and target.is_file():
                    target_matches = hashlib.sha256(target.read_bytes()).hexdigest() == source_sha256
                if force or not target_matches:
                    shutil.copy2(source, target)
                if hashlib.sha256(target.read_bytes()).hexdigest() != source_sha256:
                    raise ValueError("preserved source hash does not match the Raw source")
                prepared[cache_key] = target

            row["savedCarSource"] = str(target.relative_to(derived)).replace("\\", "/")
            row["savedCarSourceSha256"] = source_sha256
        except Exception as exc:
            warnings.append(f"Could not preserve official SavedCar source {source.name}: {exc}")

    return {
        "count": len({str(path).lower() for path in prepared.values()}),
        "warnings": warnings,
    }


def resolve_variant_final_state(
    preview_assets_root: str | Path,
    car_model: Any,
    vehicle_variant: dict[str, Any] | None,
) -> dict[str, Any]:
    clean_car = official_car_resources.safe_car_id(car_model, "")
    variant = vehicle_variant if isinstance(vehicle_variant, dict) else {}
    raw_relative_text = str(variant.get("carFinalState") or "").strip()
    derived_relative_text = str(variant.get("savedCarSource") or "").strip()
    result: dict[str, Any] = {
        "ready": False,
        "carModel": clean_car,
        "relativePath": derived_relative_text or raw_relative_text,
        "path": "",
        "sourceType": "",
        "inspection": {},
        "errors": [],
    }
    if not clean_car:
        result["errors"].append("Target car is missing.")
        return result
    if not derived_relative_text and not raw_relative_text:
        result["errors"].append("Selected vehicle variant has no prepared car final state source.")
        return result

    source: Path | None = None
    missing_candidates: list[Path] = []
    if derived_relative_text:
        derived_parts = [part for part in derived_relative_text.replace("\\", "/").lstrip("/").split("/") if part]
        if not derived_parts or any(part in {".", ".."} for part in derived_parts):
            result["errors"].append(f"Prepared SavedCar source has an unsafe path: {derived_relative_text}")
            return result
        derived_root = official_car_resources.derived_car_root(preview_assets_root, clean_car)
        candidate = derived_root / Path(*derived_parts)
        try:
            candidate.resolve().relative_to(derived_root.resolve())
        except Exception:
            result["errors"].append(f"Prepared SavedCar source resolves outside the car resources: {candidate}")
            return result
        if candidate.exists() and candidate.is_file():
            source = candidate
            result["sourceType"] = "derived_saved_car_source"
        else:
            missing_candidates.append(candidate)

    if source is None and raw_relative_text:
        try:
            relative = _content_relative_path(raw_relative_text)
        except Exception as exc:
            result["errors"].append(str(exc))
            return result
        raw_root = official_car_resources.raw_root(preview_assets_root)
        candidate = raw_root / relative
        try:
            candidate.resolve().relative_to(raw_root.resolve())
        except Exception:
            result["errors"].append(f"Car final state resolves outside Official Preview Assets: {candidate}")
            return result
        if candidate.exists() and candidate.is_file():
            source = candidate
            result["sourceType"] = "raw_preview_assets"
        else:
            missing_candidates.append(candidate)

    if source is None:
        result["errors"].append(
            "Prepared car final state is missing: " + "; ".join(str(path) for path in missing_candidates)
        )
        return result
    result["path"] = str(source)

    expected_sha256 = str(variant.get("savedCarSourceSha256") or "").strip().lower()
    if result["sourceType"] == "derived_saved_car_source" and expected_sha256:
        actual_sha256 = hashlib.sha256(source.read_bytes()).hexdigest()
        if actual_sha256 != expected_sha256:
            result["errors"].append("Prepared SavedCar source no longer matches its preview-assets manifest.")
            return result

    inspection = official_saved_car_state.inspect_saved_car_file(source)
    result["inspection"] = inspection
    if not inspection.get("valid"):
        result["errors"].append("Prepared car final state is not a supported protobuf final state.")
    if inspection.get("wrapped"):
        result["errors"].append("Prepared creator source must be a raw .carfinalstate file.")
    if str(inspection.get("carModel") or "").strip().lower() != clean_car.lower():
        result["errors"].append(
            f"Prepared car final state targets {inspection.get('carModel') or '-'}, expected {clean_car}."
        )
    for variant_key, inspection_key, label in (
        ("mechanicalPreset", "mechanicalPreset", "mechanical preset"),
        ("visualPreset", "visualPreset", "visual preset"),
    ):
        expected = str(variant.get(variant_key) or "").replace("/", "\\").lower()
        actual = str(inspection.get(inspection_key) or "").replace("/", "\\").lower()
        if expected and actual and expected != actual:
            result["errors"].append(f"Prepared car final state does not match the selected {label}.")
    result["ready"] = not result["errors"]
    return result


def generate_saved_car(
    source_path: str | Path,
    *,
    expected_car_model: str = "",
    reserved_guids: Iterable[str] | None = None,
    guid_factory: Callable[[], str] | None = None,
) -> dict[str, Any]:
    source = Path(source_path).expanduser()
    source_data = source.read_bytes()
    source_inspection = official_saved_car_state.inspect_saved_car_bytes(source_data, source.name)
    if not source_inspection.get("valid"):
        raise ValueError(f"SavedCar source is not a valid car final state: {source}")
    unwrapped = official_saved_car_state.unwrap_saved_car_state(source_data)
    inner_data = bytes(unwrapped.get("innerData") or b"")
    if not inner_data:
        raise ValueError(f"SavedCar source has no inner car final state: {source}")
    car_model = str(source_inspection.get("carModel") or "").strip()
    if expected_car_model and car_model.lower() != str(expected_car_model).strip().lower():
        raise ValueError(f"SavedCar source targets {car_model or '-'}, expected {expected_car_model}.")

    patched_inner, mappings = regenerate_instance_guids(
        inner_data,
        reserved_guids=reserved_guids,
        guid_factory=guid_factory,
    )
    source_car_guid = official_saved_car_state.normalize_guid(source_inspection.get("carGuid"))
    car_mappings = [row for row in mappings if row.get("oldGuid") == source_car_guid]
    if len(car_mappings) != 1:
        raise ValueError(f"Expected one car GUID pair in SavedCar source, found {len(car_mappings)}.")
    generated_guids = [str(row.get("newGuid") or "") for row in mappings]
    if len(generated_guids) != len(set(generated_guids)):
        raise ValueError("Generated SavedCar instance GUIDs are not unique.")
    if not generated_guids or not all(guid.startswith(KUNOS_DYNAMIC_GUID_PREFIX) for guid in generated_guids):
        raise ValueError("Generated SavedCar GUIDs do not match the observed Kunos dynamic GUID format.")
    if normalize_instance_guids_for_comparison(patched_inner) != normalize_instance_guids_for_comparison(inner_data):
        raise ValueError("Generated SavedCar differs from its source outside instance GUID fields.")

    car_guid = str(car_mappings[0]["newGuid"])
    patched_inner = set_livery_linker(patched_inner, car_guid)
    filename = f"{car_model}_{car_guid}{official_saved_car_state.SAVED_CAR_SUFFIX}"
    wrapped_data = wrap_car_final_state(patched_inner)
    inspection = official_saved_car_state.inspect_saved_car_bytes(wrapped_data, filename)
    if not inspection.get("valid") or not inspection.get("wrapped"):
        raise ValueError("Generated SavedCar wrapper failed validation.")
    if (
        inspection.get("carGuid") != car_guid
        or inspection.get("filenameGuid") != car_guid
        or inspection.get("liveryLinkerGuid") != car_guid
    ):
        raise ValueError("Generated SavedCar filename, inner car GUID and livery linker do not match.")
    if inspection.get("warnings") or inspection.get("errors"):
        raise ValueError("Generated SavedCar contains validation warnings or errors.")

    return {
        "data": wrapped_data,
        "filename": filename,
        "carGuid": car_guid,
        "carModel": car_model,
        "sourcePath": str(source),
        "sourceSha256": _sha256_bytes(source_data),
        "sha256": _sha256_bytes(wrapped_data),
        "size": len(wrapped_data),
        "instanceGuidCount": len(mappings),
        "instanceGuidMappings": mappings,
        "inspection": inspection,
    }


def write_project_saved_car(
    project_folder: str | Path,
    generated: dict[str, Any],
    *,
    source_relative_path: str = "",
    overwrite: bool = False,
) -> dict[str, Any]:
    project = Path(project_folder).expanduser()
    filename = Path(str(generated.get("filename") or "")).name
    data = generated.get("data")
    if not filename or not isinstance(data, (bytes, bytearray)):
        raise ValueError("Generated SavedCar payload is incomplete.")
    folder = project / PROJECT_SAVED_CAR_DIRNAME
    target = folder / filename
    if target.exists() and not overwrite:
        if _sha256_bytes(target.read_bytes()) != str(generated.get("sha256") or ""):
            raise FileExistsError(f"Project SavedCar already exists with different content: {target}")
    else:
        folder.mkdir(parents=True, exist_ok=True)
        temp = target.with_name(target.name + ".tmp")
        temp.write_bytes(bytes(data))
        os.replace(temp, target)
    inspection = official_saved_car_state.inspect_saved_car_file(target)
    if not inspection.get("valid") or inspection.get("carGuid") != generated.get("carGuid"):
        raise ValueError(f"Written project SavedCar failed validation: {target}")
    relative_path = f"{PROJECT_SAVED_CAR_DIRNAME}/{filename}"
    return {
        "sourceType": SOURCE_LIVERYLAB_GENERATED,
        "relativePath": relative_path,
        "path": str(target),
        "filename": filename,
        "carGuid": generated.get("carGuid") or "",
        "carModel": generated.get("carModel") or "",
        "sourceFinalState": source_relative_path,
        "sourceSha256": generated.get("sourceSha256") or "",
        "sha256": generated.get("sha256") or "",
        "size": generated.get("size") or len(data),
        "instanceGuidCount": generated.get("instanceGuidCount") or 0,
        "instanceGuidMappings": list(generated.get("instanceGuidMappings") or []),
        "createdAt": datetime.now().isoformat(timespec="seconds"),
        "deploymentStatus": "prepared_local",
    }


def project_saved_car_status(
    entry: dict[str, Any],
    project_folder: str | Path,
    preview_assets_root: str | Path | None = None,
) -> dict[str, Any]:
    project = Path(project_folder).expanduser()
    details = entry.get("official_external") if isinstance(entry.get("official_external"), dict) else {}
    generated = details.get("generatedSavedCar") if isinstance(details.get("generatedSavedCar"), dict) else {}
    files = entry.get("files") if isinstance(entry.get("files"), dict) else {}
    relative_text = str(generated.get("relativePath") or files.get("saved_car") or "").strip()
    result: dict[str, Any] = {
        "managed": str(details.get("savedCarSource") or generated.get("sourceType") or "").strip().lower()
        in DEPLOYABLE_SAVED_CAR_SOURCES,
        "sourceType": str(details.get("savedCarSource") or generated.get("sourceType") or "").strip(),
        "relativePath": relative_text,
        "path": "",
        "exists": False,
        "valid": False,
        "carGuid": "",
        "instanceCarGuid": "",
        "liveryLinkerGuid": "",
        "carModel": "",
        "inspection": {},
        "officialExternalCompatibility": {},
        "warnings": [],
        "errors": [],
    }
    if not relative_text:
        return result
    relative = Path(*[part for part in relative_text.replace("\\", "/").split("/") if part])
    target = project / relative
    try:
        target.resolve().relative_to(project.resolve())
    except Exception:
        result["errors"].append("Project SavedCar path resolves outside the project folder.")
        return result
    result["path"] = str(target)
    result["exists"] = target.exists() and target.is_file()
    if not result["exists"]:
        result["errors"].append(f"Prepared project SavedCar is missing: {target}")
        return result
    inspection = official_saved_car_state.inspect_saved_car_file(target)
    result["inspection"] = inspection
    details = entry.get("official_external") if isinstance(entry.get("official_external"), dict) else {}
    metadata = details.get("metadata") if isinstance(details.get("metadata"), dict) else {}
    variant = details.get("vehicleVariant") or metadata.get("vehicleVariant") or entry.get("vehicle_variant") or {}
    compatibility = official_variant_compatibility.compatibility(
        inspection,
        variant,
        preview_assets_root=preview_assets_root,
        require_visual_flag=preview_assets_root is not None,
    )
    result["officialExternalCompatibility"] = compatibility
    result["valid"] = bool(inspection.get("valid") and inspection.get("wrapped"))
    result["instanceCarGuid"] = inspection.get("carGuid") or ""
    result["liveryLinkerGuid"] = inspection.get("liveryLinkerGuid") or ""
    result["carGuid"] = official_saved_car_state.official_livery_guid(inspection)
    result["carModel"] = inspection.get("carModel") or ""
    result["warnings"] = list(inspection.get("warnings") or [])
    result["errors"].extend(inspection.get("errors") or [])
    expected_guid = official_saved_car_state.normalize_guid(entry.get("car_guid") or generated.get("carGuid"))
    if expected_guid and not official_saved_car_state.matches_official_livery_guid(inspection, expected_guid):
        result["errors"].append("Prepared project SavedCar GUID does not match the project car_guid.")
    expected_car = official_external_workflow.trusted_car_model_for_entry(
        entry,
        fallback=generated.get("carModel"),
    ).lower()
    if expected_car and str(result["carModel"] or "").strip().lower() != expected_car:
        result["errors"].append("Prepared project SavedCar targets a different car model.")
    if not compatibility.get("compatible"):
        result["errors"].append(
            str(compatibility.get("reason") or "Prepared project SavedCar is not compatible with Official External Liveries.")
        )
    result["valid"] = bool(result["valid"] and not result["errors"])
    return result


def repair_missing_project_saved_car(
    entry: dict[str, Any],
    project_folder: str | Path,
    preview_assets_root: str | Path,
) -> dict[str, Any]:
    status = project_saved_car_status(entry, project_folder, preview_assets_root)
    if not status.get("managed"):
        return {"status": "not_needed", "savedCar": status}

    compatibility = status.get("officialExternalCompatibility") if isinstance(status.get("officialExternalCompatibility"), dict) else {}
    repair_incompatible = bool(status.get("exists") and not compatibility.get("compatible"))
    if status.get("exists") and not repair_incompatible:
        return {"status": "not_needed", "savedCar": status}

    details = entry.get("official_external") if isinstance(entry.get("official_external"), dict) else {}
    generated = details.get("generatedSavedCar") if isinstance(details.get("generatedSavedCar"), dict) else {}
    expected_car_model = official_external_workflow.trusted_car_model_for_entry(
        entry,
        fallback=generated.get("carModel"),
    )
    mappings = generated.get("instanceGuidMappings") if isinstance(generated.get("instanceGuidMappings"), list) else []
    desired_guids = [official_saved_car_state.normalize_guid(row.get("newGuid")) for row in mappings if isinstance(row, dict)]
    if not desired_guids or any(not guid for guid in desired_guids):
        return {"status": "unavailable", "savedCar": status, "reason": "Stored SavedCar GUID mappings are incomplete."}

    metadata = details.get("metadata") if isinstance(details.get("metadata"), dict) else {}
    variant = details.get("vehicleVariant") or metadata.get("vehicleVariant") or entry.get("vehicle_variant") or {}
    source = resolve_variant_final_state(preview_assets_root, expected_car_model, variant)
    if repair_incompatible:
        source = resolve_compatible_variant_final_state(
            preview_assets_root,
            expected_car_model,
            variant,
        )
    if not source.get("ready"):
        return {
            "status": "unavailable",
            "savedCar": status,
            "reason": "; ".join(str(row) for row in source.get("errors") or []) or "SavedCar generation source is unavailable.",
        }

    guid_iter = iter(desired_guids)
    try:
        rebuilt = generate_saved_car(
            source["path"],
            expected_car_model=expected_car_model,
            guid_factory=lambda: next(guid_iter),
        )
    except (StopIteration, ValueError) as exc:
        return {"status": "unavailable", "savedCar": status, "reason": str(exc)}

    expected_guid = official_saved_car_state.normalize_guid(entry.get("car_guid") or generated.get("carGuid"))
    if expected_guid and rebuilt.get("carGuid") != expected_guid:
        return {"status": "unavailable", "savedCar": status, "reason": "Rebuilt SavedCar GUID does not match the project."}
    expected_hash = str(generated.get("sha256") or "").strip().lower()
    if not repair_incompatible and expected_hash and str(rebuilt.get("sha256") or "").lower() != expected_hash:
        return {"status": "unavailable", "savedCar": status, "reason": "Rebuilt SavedCar checksum does not match the original project file."}

    written = write_project_saved_car(
        project_folder,
        rebuilt,
        source_relative_path=str(generated.get("sourceFinalState") or source.get("relativePath") or ""),
        overwrite=True,
    )
    return {
        "status": "repaired_incompatible" if repair_incompatible else "repaired",
        "savedCar": project_saved_car_status(entry, project_folder, preview_assets_root),
        "metadata": written,
        "reason": compatibility.get("reason") or "",
    }


def resolve_compatible_variant_final_state(
    preview_assets_root: str | Path,
    car_model: str,
    vehicle_variant: dict[str, Any] | None,
) -> dict[str, Any]:
    clean_car = official_car_resources.safe_car_id(car_model, "")
    variant = vehicle_variant if isinstance(vehicle_variant, dict) else {}
    mechanical = str(variant.get("mechanicalPreset") or "").replace("/", "\\").lower()
    requested_visual = str(variant.get("visualPreset") or "").replace("/", "\\").lower()
    source_root = official_car_resources.derived_car_root(preview_assets_root, clean_car) / "SavedCarSources"
    manifest_variants: list[dict[str, Any]] = []
    manifest_path = official_car_resources.derived_manifest_path(preview_assets_root, clean_car)
    if manifest_path.is_file():
        try:
            manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
            manifest_variants = [
                row for row in manifest.get("vehicleVariants", [])
                if isinstance(row, dict)
            ]
        except Exception:
            manifest_variants = []

    def variant_for_visual(visual_preset: Any) -> dict[str, Any]:
        wanted = str(visual_preset or "").replace("/", "\\").lower()
        for row in manifest_variants:
            aliases = [row] + [
                alias for alias in row.get("sourceVariants", [])
                if isinstance(alias, dict)
            ]
            for alias in aliases:
                actual = str(alias.get("visualPreset") or "").replace("/", "\\").lower()
                if wanted and actual == wanted:
                    return {**row, **alias}
        return {}

    candidates: list[tuple[int, int, Path, dict[str, Any], dict[str, Any]]] = []
    if source_root.exists():
        for path in source_root.glob("*.carfinalstate"):
            inspection = official_saved_car_state.inspect_saved_car_file(path)
            if not inspection.get("valid") or inspection.get("wrapped"):
                continue
            actual_mechanical = str(inspection.get("mechanicalPreset") or "").replace("/", "\\").lower()
            if mechanical and actual_mechanical != mechanical:
                continue
            matched_variant = variant_for_visual(inspection.get("visualPreset"))
            compatibility = official_variant_compatibility.compatibility(
                inspection,
                matched_variant,
                preview_assets_root=preview_assets_root,
            )
            if not compatibility.get("compatible"):
                continue
            stems = compatibility.get("materialStems") or []
            actual_visual = str(inspection.get("visualPreset") or "").replace("/", "\\").lower()
            visual_score = 0 if requested_visual and actual_visual == requested_visual else 1
            material_score = 0 if "EXT_SKIN" in stems else 1
            candidates.append((visual_score, material_score, path, inspection, compatibility))
    if not candidates:
        return {
            "ready": False,
            "carModel": clean_car,
            "path": "",
            "inspection": {},
            "errors": ["No compatible Official External SavedCar source was found for the selected mechanical variant."],
        }
    _, _, path, inspection, compatibility = sorted(
        candidates,
        key=lambda row: (row[0], row[1], str(row[2]).lower()),
    )[0]
    return {
        "ready": True,
        "carModel": clean_car,
        "relativePath": str(path.relative_to(official_car_resources.derived_car_root(preview_assets_root, clean_car))).replace("\\", "/"),
        "path": str(path),
        "sourceType": "derived_compatible_saved_car_source",
        "inspection": inspection,
        "compatibility": compatibility,
        "errors": [],
    }
