"""Pure BeamNG material declaration and texture-resolution helpers.

This module deliberately has no Blender dependency so the importer can test the
source decision model without starting an editor. The Blender converter consumes
the same structures rather than maintaining a second first-stage-only parser.
"""
from __future__ import annotations

import json
import os
import re
from pathlib import Path


MAP_ROLES = {
    "basecolormap": "baseColor",
    "colormap": "baseColor",
    "diffusemap": "baseColor",
    "normalmap": "normal",
    "roughnessmap": "roughness",
    "metallicmap": "metallic",
    "ambientocclusionmap": "occlusion",
    "opacitymap": "opacity",
    "emissivemap": "emissive",
    "detailmap": "detail",
    "detailnormalmap": "detailNormal",
    "specularmap": "specular",
    "colorpalettemap": "colorPalette",
    "clearcoatmap": "clearCoat",
}
FACTOR_KEYS = {
    "baseColorFactor", "diffuseColor", "metallicFactor", "roughnessFactor",
    "opacityFactor", "emissiveFactor", "clearCoatFactor", "clearCoatRoughnessFactor",
}
TEXTURE_EXTENSIONS = (".dds", ".png", ".jpg", ".jpeg", ".tga", ".bmp")


def _strip_json_comments(text: str) -> str:
    output, index, quoted, escaped = [], 0, False, False
    while index < len(text):
        char = text[index]
        if quoted:
            output.append(char)
            if escaped:
                escaped = False
            elif char == "\\":
                escaped = True
            elif char == '"':
                quoted = False
            index += 1
            continue
        if char == '"':
            quoted = True
            output.append(char)
            index += 1
        elif text.startswith("//", index):
            end = text.find("\n", index)
            index = len(text) if end < 0 else end
        elif text.startswith("/*", index):
            end = text.find("*/", index + 2)
            index = len(text) if end < 0 else end + 2
        else:
            output.append(char)
            index += 1
    return "".join(output)


def _load_json(path: Path) -> dict:
    text = _strip_json_comments(path.read_text(errors="ignore"))
    text = re.sub(r",\s*([}\]])", r"\1", text)
    value = json.loads(text)
    return value if isinstance(value, dict) else {}


def _portable(path: Path, root: Path) -> str:
    return str(path.relative_to(root)).replace(os.sep, "/")


def _normalize_map(name: str) -> str:
    return name.strip().strip('"').replace("\\", "/").lstrip("/")


def is_dynamic_texture(name: object) -> bool:
    return isinstance(name, str) and name.strip().startswith("@")


def is_sentinel_map(name: object) -> bool:
    if not isinstance(name, str):
        return False
    base = os.path.basename(_normalize_map(name)).lower()
    stem = base.split(".")[0]
    return stem == "null" or stem.startswith("null_")


def _alpha(raw: dict) -> dict:
    translucent = bool(raw.get("translucent"))
    alpha_test = bool(raw.get("alphaTest"))
    if translucent and alpha_test:
        ref = raw.get("alphaRef")
        cutoff = float(ref) / 255.0 if isinstance(ref, (int, float)) and ref else 0.5
        return {"mode": "MASK", "cutoff": cutoff, "source": "materials.json",
                "declaredBy": {key: raw[key] for key in
                               ("translucent", "alphaTest", "alphaRef", "translucentBlendOp") if key in raw}}
    return {"mode": "BLEND" if translucent else "OPAQUE", "source": "materials.json",
            "declaredBy": {key: raw[key] for key in
                           ("translucent", "alphaTest", "alphaRef", "translucentBlendOp") if key in raw}}


def _material(key: str, raw: dict, path: Path, root: Path, tier: str) -> tuple[dict, dict[str, list]]:
    stages = raw.get("Stages") if isinstance(raw.get("Stages"), list) else []
    maps, ordered_maps, factors = {}, [], {}
    diagnostics = {"stageConflicts": [], "dynamicTextures": [], "sentinels": [], "unsupportedMaps": []}
    identity = str(raw.get("mapTo") or raw.get("name") or key).strip()
    for stage_index, stage in enumerate(stages):
        if not isinstance(stage, dict):
            continue
        for source_key, value in stage.items():
            lower = source_key.lower()
            role = MAP_ROLES.get(lower)
            if role is None and lower.endswith("map"):
                role = source_key[:-3]
            if role and isinstance(value, str) and value.strip():
                name = value.strip()
                event = {
                    "material": identity, "role": role, "name": name, "stage": stage_index,
                    "declarationTier": tier, "declarationFile": _portable(path, root),
                    "declarationKey": key, "sourceKey": source_key,
                }
                if is_sentinel_map(name):
                    diagnostics["sentinels"].append(event)
                    continue
                if is_dynamic_texture(name):
                    diagnostics["dynamicTextures"].append(event)
                    continue
                clean = _normalize_map(name)
                previous = maps.get(role)
                if previous is not None and previous != clean:
                    diagnostics["stageConflicts"].append({
                        "material": identity, "role": role, "kept": clean, "dropped": previous,
                        "stage": stage_index, "declarationTier": tier,
                        "declarationFile": _portable(path, root), "declarationKey": key,
                        "why": "later BeamNG material stage wins; both source declarations remain in provenance",
                    })
                maps[role] = clean
                ordered_maps.append({"role": role, "name": clean, "stage": stage_index, "sourceKey": source_key})
                if role not in {"baseColor", "normal", "roughness", "metallic", "occlusion", "opacity", "emissive", "colorPalette"}:
                    diagnostics["unsupportedMaps"].append(event)
            if source_key in FACTOR_KEYS:
                factors[source_key] = {"value": value, "stage": stage_index, "source": "materials.json"}
    row = {
        "key": key,
        "mapTo": identity,
        "stageCount": len(stages),
        "stages": stages,
        "maps": maps,
        "orderedMaps": ordered_maps,
        "factors": factors,
        "alpha": _alpha(raw),
        "doubleSided": bool(raw.get("doubleSided")) if "doubleSided" in raw else None,
        "provenance": {
            "declarationTier": tier,
            "declarationFile": _portable(path, root),
            "declarationKey": key,
            "mapTo": identity,
        },
    }
    for field, role in (("base", "baseColor"), ("paletteMask", "colorPalette"), ("normal", "normal"),
                        ("roughnessMap", "roughness"), ("metallicMap", "metallic")):
        row[field] = maps.get(role)
    for field in ("metallic", "roughness"):
        source = factors.get(f"{field}Factor")
        row[field] = source.get("value") if source else None
    color = factors.get("baseColorFactor") or factors.get("diffuseColor")
    row["color"] = color.get("value") if color else None
    row["alphaDeclared"] = row["alpha"]["mode"] != "OPAQUE"
    return row, diagnostics


def parse_material_tree(root: str | Path, default_tier: str = "mod", vehicle_root: str | Path | None = None) -> dict:
    root_path = Path(root).resolve()
    vehicle_path = Path(vehicle_root).resolve() if vehicle_root else None
    materials, aliases = {}, {}
    diagnostics = {
        "parseFailures": [], "shadowedDeclarations": [], "stageConflicts": [],
        "dynamicTextures": [], "sentinels": [], "unsupportedMaps": [],
    }
    paths = sorted(root_path.rglob("*.materials.json")) if root_path.is_dir() else []
    for path in paths:
        try:
            document = _load_json(path)
        except Exception as error:
            diagnostics["parseFailures"].append({"file": _portable(path, root_path), "error": str(error)})
            continue
        tier = "vehicle" if vehicle_path and (path == vehicle_path or vehicle_path in path.parents) else default_tier
        for key, raw in document.items():
            if not isinstance(raw, dict):
                continue
            row, row_diagnostics = _material(str(key), raw, path, root_path, tier)
            identity = row["mapTo"].lower()
            existing = materials.get(identity)
            if existing:
                ranks = {"basegame": 0, "mod": 1, "vehicle": 2}
                existing_rank = ranks.get(existing["provenance"]["declarationTier"], 0)
                current_rank = ranks.get(tier, 0)
                if existing_rank > current_rank:
                    diagnostics["shadowedDeclarations"].append({
                        "material": identity, "kept": existing["provenance"], "ignored": row["provenance"]})
                    continue
                diagnostics["shadowedDeclarations"].append({
                    "material": identity, "kept": row["provenance"], "ignored": existing["provenance"]})
            materials[identity] = row
            aliases[str(key).lower()] = identity
            aliases[row["mapTo"].lower()] = identity
            for name, values in row_diagnostics.items():
                diagnostics[name].extend(values)
    return {"materials": materials, "aliases": aliases, "diagnostics": diagnostics}


class TextureChain:
    """Most-specific-first texture lookup with explicit ambiguity and provenance."""

    def __init__(self, roots: list[tuple[str, str | Path]]):
        self.roots = [(tier, Path(root).resolve()) for tier, root in roots if Path(root).is_dir()]
        self.index: dict[str, dict[str, list[Path]]] = {}
        for tier, root in self.roots:
            tier_index: dict[str, list[Path]] = {}
            for path in sorted(root.rglob("*")):
                if not path.is_file() or path.suffix.lower() not in TEXTURE_EXTENSIONS:
                    continue
                rel = _portable(path, root).lower()
                tier_index.setdefault(rel, []).append(path)
                tier_index.setdefault(path.name.lower(), []).append(path)
            self.index[tier] = tier_index

    def resolve(self, raw: object) -> dict:
        if not isinstance(raw, str) or not raw.strip():
            return {"resolved": False, "reason": "empty"}
        if is_dynamic_texture(raw):
            return {"resolved": False, "dynamic": True, "name": raw}
        if is_sentinel_map(raw):
            return {"resolved": False, "sentinel": True, "name": raw}
        requested = _normalize_map(raw).lower()
        stem, extension = os.path.splitext(requested)
        full_candidates = [requested]
        if extension not in TEXTURE_EXTENSIONS:
            full_candidates.extend(requested + suffix for suffix in TEXTURE_EXTENSIONS)
            full_candidates.extend(stem + suffix for suffix in TEXTURE_EXTENSIONS)
        basename_candidates = [os.path.basename(value) for value in full_candidates]
        for tier, _root in self.roots:
            tier_index = self.index[tier]
            for candidate_group in (full_candidates, basename_candidates):
                hits = sorted({path for candidate in candidate_group for path in tier_index.get(candidate, [])})
                if len(hits) == 1:
                    hit = hits[0]
                    return {"resolved": True, "name": raw, "path": hit, "tier": tier,
                            "matched": candidate_group[0], "corrected": hit.name.lower() != os.path.basename(requested)}
                if len(hits) > 1:
                    return {"resolved": False, "name": raw, "tier": tier, "reason": "ambiguous",
                            "candidates": [str(path) for path in hits]}
        return {"resolved": False, "name": raw, "reason": "missing", "searched": [tier for tier, _ in self.roots],
                "remedy": "supply the exact texture in the source or digest-bound BeamNG common dependency"}
