# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Agent trust metric computation: accuracy, predictions, contradictions, longevity."""
import json
from datetime import datetime, timezone
from pulse.core.brain_utils import STATE_DIR, LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL, read_jsonl_entries


def _compute_accuracy(agent_name: str) -> tuple[int, int, float]:
    """Count JSONL entries by source. Returns (contributions, survived, accuracy_rate)."""
    contributions = 0
    survived = 0
    name_lower = agent_name.lower()
    for jsonl_path in (LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL):
        try:
            entries = read_jsonl_entries(jsonl_path)
        except Exception:
            continue
        for e in entries:
            src = (e.get("agent", "") or e.get("source", "")).lower()
            if name_lower in src or src in name_lower:
                contributions += 1
                if e.get("consolidation_count", 1) > 1:
                    survived += 1
    rate = survived / contributions if contributions > 0 else 0.0
    return contributions, survived, round(rate, 4)


def _compute_prediction_accuracy(agent_name: str) -> tuple[int, int, float]:
    """Read prediction metrics. Returns (correct, total, accuracy)."""
    try:
        from pulse.daemons.neural.prediction_feedback import get_prediction_accuracy
        data = get_prediction_accuracy()
        return data.get("correct", 0), data.get("total", 0), data.get("accuracy", 0.0)
    except Exception:
        return 0, 0, 0.0


def _compute_contradiction_rate(agent_name: str) -> tuple[int, float]:
    """Returns (contradictions_involved, inverse_rate)."""
    try:
        reg_file = STATE_DIR / "contradiction_registry.json"
        if not reg_file.exists():
            return 0, 1.0
        data = json.loads(reg_file.read_text(encoding="utf-8"))
        name_lower = agent_name.lower()
        involved = 0
        for ctr in data.get("contradictions", []):
            for side in ("item_a", "item_b"):
                item = ctr.get(side, {})
                src = (item.get("source", "") or item.get("file", "")).lower()
                if name_lower in src:
                    involved += 1
                    break
        return involved, 1.0
    except Exception:
        return 0, 1.0


def _compute_longevity(agent_name: str, first_seen: str) -> float:
    """Days since first_seen / 30, capped at 1.0."""
    if not first_seen:
        return 0.0
    try:
        dt = datetime.fromisoformat(first_seen.replace("Z", "+00:00"))
        days = (datetime.now(timezone.utc) - dt).total_seconds() / 86400
        return min(1.0, round(days / 30, 4))
    except (ValueError, TypeError):
        return 0.0


def _find_first_seen(agent_name: str) -> str:
    """Scan JSONL entries to find earliest timestamp for agent."""
    earliest = ""
    name_lower = agent_name.lower()
    for jsonl_path in (LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL):
        try:
            for e in read_jsonl_entries(jsonl_path):
                src = (e.get("agent", "") or e.get("source", "")).lower()
                if name_lower in src or src in name_lower:
                    ts = e.get("timestamp", "")
                    if ts and (not earliest or ts < earliest):
                        earliest = ts
        except Exception:
            continue
    return earliest
