#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Task complexity estimation — Item 144 (P34 neuroscience).

Estimates task complexity from brain: anti-patterns + failure count for domain.
High complexity = route to premium tier.
"""
import logging
from typing import Dict, Any

log = logging.getLogger("pulse.tasks.task_complexity")

_HIGH_COMPLEXITY_SCORE = 6   # combined score above this = premium
_ANTIPATTERN_WEIGHT = 1      # each anti-pattern adds this to score
_FAILURE_WEIGHT = 1          # each failure adds this to score


def estimate_task_complexity(task: Dict[str, Any]) -> Dict[str, Any]:
    """Estimate complexity from brain knowledge: anti-patterns + failures in domain.

    Returns: {complexity_score, antipattern_count, failure_count, suggested_tier}
    Fails open with complexity_score=0, suggested_tier=None on error.
    """
    result: Dict[str, Any] = {
        "complexity_score": 0,
        "antipattern_count": 0,
        "failure_count": 0,
        "suggested_tier": None,
    }
    try:
        domain = (task.get("domain") or task.get("type") or "general").lower()
        ap_count = _count_antipatterns(domain)
        fail_count = _count_failures(domain)
        score = ap_count * _ANTIPATTERN_WEIGHT + fail_count * _FAILURE_WEIGHT
        current_tier = task.get("recommended_tier") or task.get("tier")
        suggested = current_tier
        if score >= _HIGH_COMPLEXITY_SCORE and current_tier != "premium":
            suggested = "premium"
        elif score >= 3 and current_tier == "fast":
            suggested = "standard"
        result.update({
            "complexity_score": score,
            "antipattern_count": ap_count,
            "failure_count": fail_count,
            "suggested_tier": suggested,
        })
    except Exception as exc:
        log.debug("estimate_task_complexity failed: %s", exc)
    return result


def _count_antipatterns(domain: str) -> int:
    """Count anti-patterns in domain using brain DB. Fail open = 0."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        try:
            row = conn.execute(
                "SELECT COUNT(*) FROM anti_patterns WHERE domain = ?", (domain,)
            ).fetchone()
            return int(row[0] or 0)
        except Exception:
            row = conn.execute(
                "SELECT COUNT(*) FROM patterns WHERE domain = ? AND confidence >= 0.5",
                (domain,),
            ).fetchone()
            return int(row[0] or 0)
    except Exception:
        return 0


def _count_failures(domain: str) -> int:
    """Count failures in domain using brain DB. Fail open = 0."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        row = conn.execute(
            "SELECT COUNT(*) FROM failures WHERE domain = ? AND validity = 'valid'",
            (domain,),
        ).fetchone()
        return int(row[0] or 0)
    except Exception:
        return 0


def apply_complexity_routing(tasks: list) -> None:
    """Mutate tasks in-place: upgrade tier based on brain complexity. Fails open."""
    try:
        for task in tasks:
            if task.get("status") == "rejected":
                continue
            complexity = estimate_task_complexity(task)
            task["_complexity"] = complexity
            suggested = complexity.get("suggested_tier")
            if suggested and suggested != task.get("recommended_tier"):
                task["_original_tier"] = task.get("recommended_tier")
                task["recommended_tier"] = suggested
    except Exception as exc:
        log.debug("apply_complexity_routing failed: %s", exc)
