"""Property assignment from JSON-friendly dicts onto FreeCAD document objects."""

from dataclasses import dataclass, field
import math
from typing import Any

import FreeCAD


@dataclass
class Object:
    name: str
    type: str | None = None
    analysis: str | None = None
    properties: dict[str, Any] = field(default_factory=dict)


def _to_shape_color(val: Any) -> tuple[float, float, float, float]:
    """Normalise a color to a 4-float RGBA tuple.

    Accepts RGB triples (alpha defaults to 1.0) and RGBA quads, matching what
    FreeCAD's ``ShapeColor`` accepts.
    """
    if not isinstance(val, (list, tuple)) or len(val) not in (3, 4):
        raise ValueError(
            f"ShapeColor must be an RGB or RGBA sequence, got {val!r}."
        )
    r, g, b = (float(val[0]), float(val[1]), float(val[2]))
    a = float(val[3]) if len(val) == 4 else 1.0
    return (r, g, b, a)


def parse_reference_entry(entry: Any) -> tuple[str, Any]:
    """Normalise a single ``References`` entry to ``(object_name, sub_element)``.

    Accepts both the documented dict form
    ``{"object_name": "Box", "face": "Face1"}`` and the legacy
    ``["Box", "Face1"]`` pair form.
    """
    if isinstance(entry, dict):
        ref_name = entry.get("object_name", entry.get("Object"))
        face = entry.get("face", entry.get("Face"))
        if ref_name is None:
            raise ValueError(
                f"Reference entry {entry!r} is missing an 'object_name' key."
            )
        return ref_name, face
    if isinstance(entry, (list, tuple)) and len(entry) == 2:
        return entry[0], entry[1]
    raise ValueError(
        f"Invalid reference entry {entry!r}; expected "
        "{'object_name': ..., 'face': ...} or [object_name, face]."
    )


def resolve_references(doc: FreeCAD.Document, val: Any) -> list[tuple[Any, Any]]:
    """Resolve a ``References`` list into ``(DocumentObject, sub_element)`` tuples."""
    refs = []
    for entry in val:
        ref_name, face = parse_reference_entry(entry)
        ref_obj = doc.getObject(ref_name)
        if ref_obj is None:
            raise ValueError(f"Referenced object '{ref_name}' not found.")
        refs.append((ref_obj, face))
    return refs


def _resolve_link(doc: FreeCAD.Document, value: Any) -> Any:
    if value is None:
        return None
    if not isinstance(value, str):
        raise ValueError("Object links require an object name or null")
    linked = doc.getObject(value)
    if linked is None:
        raise ValueError(f"Referenced object '{value}' not found.")
    return linked


def _resolve_link_value(doc: FreeCAD.Document, kind: str, value: Any) -> Any:
    if kind == "App::PropertyLink":
        return _resolve_link(doc, value)
    if kind == "App::PropertyLinkList":
        return [_resolve_link(doc, item) for item in value]
    if kind == "App::PropertyLinkSub":
        if value is None:
            return None
        name, sub = parse_reference_entry(value)
        return (_resolve_link(doc, name), sub)
    return resolve_references(doc, value)


def set_object_property(
    doc: FreeCAD.Document, obj: FreeCAD.DocumentObject, properties: dict[str, Any]
) -> None:
    failures = []
    for prop, val in properties.items():
        try:
            # Mesh aliases must work identically when creating and editing.
            if getattr(getattr(obj, "Proxy", None), "Type", "") == "Fem::FemMeshGmsh" or (
                hasattr(obj, "FemMesh") and hasattr(obj, "CharacteristicLengthMax")
            ):
                prop = {"Part": "Shape", "ElementSizeMax": "CharacteristicLengthMax",
                        "ElementSizeMin": "CharacteristicLengthMin"}.get(prop, prop)
            if prop in obj.PropertiesList:
                if prop == "Placement" and isinstance(val, dict):
                    if "Base" in val:
                        pos = val["Base"]
                    elif "Position" in val:
                        pos = val["Position"]
                    else:
                        pos = {}
                    rot = val.get("Rotation", {})
                    placement = FreeCAD.Placement(
                        FreeCAD.Vector(
                            pos.get("x", 0),
                            pos.get("y", 0),
                            pos.get("z", 0),
                        ),
                        FreeCAD.Rotation(
                            FreeCAD.Vector(
                                rot.get("Axis", {}).get("x", 0),
                                rot.get("Axis", {}).get("y", 0),
                                rot.get("Axis", {}).get("z", 1),
                            ),
                            rot.get("Angle", 0),
                        ),
                    )
                    setattr(obj, prop, placement)

                elif prop == "Force" and obj.TypeId == "Fem::ConstraintForce":
                    if not isinstance(val, str):
                        raise ValueError("Force requires an explicit unit, e.g. '100 N'; bare numbers are ambiguous")
                    try:
                        newtons = FreeCAD.Units.Quantity(val).getValueAs("N")
                        if not math.isfinite(float(newtons.Value)):
                            raise ValueError("non-finite force")
                    except Exception as exc:
                        raise ValueError("Force requires a finite quantity with force units, e.g. '100 N'") from exc
                    setattr(obj, prop, val)

                elif prop == "Direction" and obj.TypeId == "Fem::ConstraintForce" and isinstance(val, (dict, list, tuple)):
                    if isinstance(val, dict):
                        name = val.get("object_name")
                        subs = val.get("edge", val.get("face"))
                    elif len(val) == 2:
                        name, subs = val
                    else:
                        raise ValueError("Direction needs [object_name, edge_or_face]")
                    subs = [subs] if isinstance(subs, str) else subs
                    if not isinstance(subs, (list, tuple)) or len(subs) != 1 or not isinstance(subs[0], str):
                        raise ValueError("Direction needs exactly one edge or face")
                    target = doc.getObject(name) if isinstance(name, str) else None
                    if target is None or target.getSubObject(subs[0]) is None:
                        raise ValueError(f"Direction reference {name!r}:{subs[0]} not found")
                    setattr(obj, prop, (target, list(subs)))

                elif isinstance(getattr(obj, prop), FreeCAD.Vector) and isinstance(
                    val, dict
                ):
                    vector = FreeCAD.Vector(
                        val.get("x", 0), val.get("y", 0), val.get("z", 0)
                    )
                    setattr(obj, prop, vector)

                elif prop in ["Base", "Tool", "Source", "Profile", "Shape", "Part"] and isinstance(
                    val, str
                ):
                    ref_obj = doc.getObject(val)
                    if ref_obj:
                        setattr(obj, prop, ref_obj)
                    else:
                        raise ValueError(f"Referenced object '{val}' not found.")

                elif prop == "References" and isinstance(val, list):
                    setattr(obj, prop, resolve_references(doc, val))

                elif callable(getattr(obj, "getTypeIdOfProperty", None)) and obj.getTypeIdOfProperty(prop) in {
                    "App::PropertyLink", "App::PropertyLinkList", "App::PropertyLinkSub", "App::PropertyLinkSubList",
                }:
                    setattr(obj, prop, _resolve_link_value(doc, obj.getTypeIdOfProperty(prop), val))

                else:
                    setattr(obj, prop, val)
            # ShapeColor is a property of the ViewObject
            elif prop == "ShapeColor" and isinstance(val, (list, tuple)):
                setattr(obj.ViewObject, prop, _to_shape_color(val))

            elif prop == "ViewObject" and isinstance(val, dict):
                for k, v in val.items():
                    if k == "ShapeColor":
                        setattr(obj.ViewObject, k, _to_shape_color(v))
                    else:
                        setattr(obj.ViewObject, k, v)

            else:
                setattr(obj, prop, val)

        except Exception as e:
            FreeCAD.Console.PrintError(f"Property '{prop}' assignment error: {e}\n")
            failures.append(f"{prop}: {e}")

    if failures:
        raise ValueError(
            "Failed to set propert" + ("y" if len(failures) == 1 else "ies")
            + ": " + "; ".join(failures)
        )
