"""Evolution evidence reporter — bridges learning_brain data to autonomy decisions.

Phase 2 enhancement: reads from trading_brain.db and existing data sources
instead of returning a hardcoded empty stub.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import config_manager


def build_evolution_evidence_report(
    project_root: Path | None = None,
    tenant_id: str = "default",
    lookback_days: int = 30,
) -> dict[str, Any]:
    """Build an evidence report from learning_brain, trading ledger, and
    strategy intelligence data.

    Returns:
        {"available": bool, "cycles": int, "evidence": [...], "verdict": {...}}
    """
    evidence: list[dict[str, Any]] = []
    cycles = 0

    # ── Source 1: Learning brain ──
    try:
        from src.learning.trading_brain import get_brain
        brain = get_brain()
        sizes = brain.table_sizes()

        # Win rate patterns
        rs_stats = brain.query_by_regime_session()
        for g in rs_stats:
            if g.get("n", 0) >= 5:
                evidence.append({
                    "source": "learning_brain",
                    "type": "regime_session_performance",
                    "regime": g.get("regime"),
                    "session": g.get("session"),
                    "n": g.get("n"),
                    "win_rate": g.get("win_rate"),
                    "avg_pnl": g.get("avg_pnl"),
                })
                cycles = max(cycles, g.get("n", 0))

        # Judgment accuracy
        acc = brain.query_judgment_accuracy()
        if acc.get("n", 0) >= 3:
            evidence.append({
                "source": "learning_brain",
                "type": "agent_judgment_accuracy",
                "n": acc.get("n"),
                "accuracy": acc.get("accuracy"),
                "avg_confidence": acc.get("avg_confidence"),
            })
    except Exception:
        pass

    # ── Source 2: Trading ledger (existing PnL data) ──
    try:
        ledger_path = config_manager.get_logs_dir() / "trading_ledger.ndjson"
        if ledger_path.exists():
            trades: list[dict[str, Any]] = []
            for line in ledger_path.read_text(encoding="utf-8").strip().splitlines():
                if line.strip():
                    try:
                        trades.append(json.loads(line))
                    except json.JSONDecodeError:
                        pass

            if trades:
                wins = sum(1 for t in trades if float(t.get("pnl", 0) or 0) > 0)
                total = len(trades)
                wr = wins / max(1, total)
                evidence.append({
                    "source": "trading_ledger",
                    "type": "overall_performance",
                    "total_trades": total,
                    "wins": wins,
                    "win_rate": round(wr, 4),
                })
                cycles = max(cycles, total)
    except Exception:
        pass

    # ── Verdict ──
    available = len(evidence) > 0
    verdict: dict[str, Any] = {"status": "INSUFFICIENT_EVIDENCE", "reason": "no_data"}

    if available:
        # Check win rates across evidence items
        wr_items = [e for e in evidence if "win_rate" in e]
        if wr_items:
            avg_wr = sum(e["win_rate"] for e in wr_items) / len(wr_items)
            if avg_wr >= 0.55:
                verdict = {"status": "SIGNIFICANT_OUTPERFORM", "reason": f"avg_win_rate={avg_wr:.0%}"}
            elif avg_wr < 0.35:
                verdict = {"status": "SIGNIFICANT_UNDERPERFORM", "reason": f"avg_win_rate={avg_wr:.0%}"}
            else:
                verdict = {"status": "MIXED_PERFORMANCE", "reason": f"avg_win_rate={avg_wr:.0%}"}

    return {
        "available": available,
        "cycles": cycles,
        "last_cycle_ts": None,
        "evidence": evidence,
        "verdict": verdict,
    }
