# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Crew composer utilities: tier helpers, task loading, graph risk queries."""
from __future__ import annotations
import logging
from pulse.core.brain_utils import load_json_dict, TASK_BOARD_FILE

log = logging.getLogger("pulse.crew_composer")

_COMPLEXITY_TIER = {"low": "fast", "medium": "standard", "high": "premium"}
_TIER_RANK = {"fast": 0, "standard": 1, "premium": 2}


def _tier_covers(crew_tier: str, task_tier: str) -> bool:
    """True if crew_tier is >= task_tier in capability ranking."""
    return _TIER_RANK.get(crew_tier, 0) >= _TIER_RANK.get(task_tier, 0)


def get_pending_tasks() -> list[dict]:
    """Read task board and return open tasks with domain/complexity."""
    board = load_json_dict(TASK_BOARD_FILE)
    tasks = []
    for dispatch in board.get("dispatches", []):
        for t in dispatch.get("tasks", []):
            status = t.get("status", "")
            if status in ("open", "escalated"):
                tasks.append({
                    "task_id": t.get("task_id") or t.get("id", ""),
                    "title": t.get("title", ""),
                    "domain": t.get("domain", "general"),
                    "complexity": t.get("complexity", "low"),
                    "recommended_tier": t.get("recommended_tier", "fast"),
                })
    return tasks


def _query_graph_risks(domains: set[str]) -> list[dict]:
    """Query knowledge graph for CAUSES/LEADS_TO risks related to task domains."""
    try:
        from pulse.graph.knowledge_graph_query import query_causes, query_prevents
    except ImportError:
        return []
    risks = []
    for domain in domains:
        causes = query_causes(f"failure in {domain}", max_results=3)
        for c in causes:
            if c.get("confidence", 0) >= 0.4:
                risks.append({"domain": domain, "type": "cause", "text": c["text"],
                               "relationship": c.get("relationship", "CAUSES"),
                               "confidence": c.get("confidence", 0.5)})
        prevents = query_prevents(f"failure in {domain}", max_results=3)
        for p in prevents:
            if p.get("confidence", 0) >= 0.4:
                risks.append({"domain": domain, "type": "protection", "text": p["text"],
                               "relationship": "PREVENTS", "confidence": p.get("confidence", 0.5)})
    return risks
