from __future__ import annotations

from typing import Any


DEPENDENCY_KIND_TYRE_BRAND = "tyreBrand"
DEPENDENCY_KIND_NUMBERPLATE_TEMPLATE = "numberplateTemplate"


def baked_numberplate_paths(numberplate_bake: dict[str, Any] | None) -> list[dict[str, str]]:
    bake = numberplate_bake if isinstance(numberplate_bake, dict) else {}
    surfaces = bake.get("surfaces") if isinstance(bake.get("surfaces"), dict) else {}
    rows: list[dict[str, str]] = []
    for surface_key, surface in surfaces.items():
        if not isinstance(surface, dict):
            continue
        for field, kind in (("textureRel", "numberplate_bake_texture"), ("mipsRel", "numberplate_bake_mips"), ("pngPath", "numberplate_bake_png")):
            value = str(surface.get(field) or "").strip()
            if value:
                rows.append({"surface": str(surface_key), "field": field, "kind": kind, "path": value})
    return rows


def numberplate_template_dependency(numberplate_bake: dict[str, Any] | None, variant: dict[str, Any] | None, available: bool) -> dict[str, Any] | None:
    bake = numberplate_bake if isinstance(numberplate_bake, dict) else {}
    data = variant if isinstance(variant, dict) else {}
    template_id = str(bake.get("template_id") or data.get("template_id") or "").strip()
    if not template_id:
        return None
    return {
        "kind": DEPENDENCY_KIND_NUMBERPLATE_TEMPLATE,
        "id": template_id,
        "required": False,
        "editOnly": True,
        "available": bool(available),
        "bakedFiles": baked_numberplate_paths(bake),
    }


def mark_baked_numberplate_import_state(numberplate_bake: dict[str, Any] | None, template_available: bool) -> dict[str, Any]:
    bake = dict(numberplate_bake) if isinstance(numberplate_bake, dict) else {}
    if not bake:
        return {}
    bake["template_available"] = bool(template_available)
    bake["baked_only"] = not bool(template_available)
    return bake
