# gate_resolver.py

from hiveos.runtime.chunk_runtime import chunk_objects
from hiveos.runtime.task_runtime import task_objects

# Global unresolved gates store (populated during ingestion)
unresolved_gates = {}  # key: chunk_id, value: {"depends_on": str, "gate_required": "soft" or "hard"}

def parse_symbolic_dep(dep_str):
    """Parses 'task:x.chunk:y' into (task_id, chunk_id)"""
    try:
        parts = dep_str.split('.')
        task_part = next(p for p in parts if p.startswith('task:'))
        chunk_part = next(p for p in parts if p.startswith('chunk:'))
        return task_part.split(':')[1], chunk_part.split(':')[1]
    except Exception:
        return None, None

def resolve_cross_task_gates():
    """Rerun gate resolution on any newly injected tasks"""
    resolved = []
    for chunk_id, gate in unresolved_gates.items():
        dep = gate['depends_on']
        task_id, chunk = parse_symbolic_dep(dep)
        dep_chunk_id = f"{chunk}_{task_id}"

        if dep_chunk_id in chunk_objects:
            chunk_obj = chunk_objects.get(chunk_id)
            if chunk_obj:
                chunk_obj.depends_on = dep_chunk_id
                resolved.append(chunk_id)
    for chunk_id in resolved:
        del unresolved_gates[chunk_id]

def evaluate_chunk_dependency(chunk_id, depends_on_field, gate_required="hard"):
    """
    Validates a chunk's depends_on field during ingestion.
    If symbolic and unresolved, handles based on gate_required.
    """
    if not depends_on_field:
        return None

    if depends_on_field.startswith("task:"):
        task_id, chunk = parse_symbolic_dep(depends_on_field)
        dep_chunk_id = f"{chunk}_{task_id}"
        if dep_chunk_id not in chunk_objects:
            if gate_required == "hard":
                raise ValueError(f"Unresolved hard dependency: {depends_on_field} for chunk {chunk_id}")
            else:
                unresolved_gates[chunk_id] = {
                    "depends_on": depends_on_field,
                    "gate_required": gate_required
                }
                return None
        else:
            return dep_chunk_id
    else:
        # Standard intra-task dependency
        return depends_on_field
