from typing import Dict, Any, Tuple
from ..schemas import OverallState


def create_validate_node():
    def validate_node(state: OverallState):
        res = state.get("final_result", {}) or {}
        missing = []

        def get_in(d: Dict[str, Any], path: Tuple[str, ...]) -> Dict[str, Any]:
            cur = d
            for p in path:
                if not isinstance(cur, dict):
                    return {}
                cur = cur.get(p, {})
            return cur if isinstance(cur, dict) else {}

        for t in state["tasks"]:
            scope = get_in(res, t.path)
            for k in t.keys:
                if not str(scope.get(k, "")).strip():
                    missing.append((".".join(t.path + (k,))) if t.path else k)

        if missing:
            return {"errors": {"missing_fields": missing}}
        return {}
    
    return validate_node
