#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
Benchmark Synthesizer: Convert benchmark outcomes to lessons (V43.12)

Pipeline: Benchmark outcome -> Evidence -> Pattern/Lesson -> Brain Map update.
Achieved benchmarks become WIN evidence. Failed become FAIL evidence (weighted 2.5x).

Usage:
    python .claude/automation/benchmark_synthesizer.py --synthesize-all
    python .claude/automation/benchmark_synthesizer.py --synthesize BM-001
    python .claude/automation/benchmark_synthesizer.py --dry-run
Dependencies: Python stdlib only (Law 4)
"""

import json
import sys
from datetime import date, datetime, timezone
from pathlib import Path

# Add Utilities to path for brain_utils

from pulse.core.brain_utils import (load_config, load_json, load_json_dict, save_json,
                         extract_domain, text_similarity,
                         BENCHMARKS_FILE, EVIDENCE_DIR, GROWTH_METRICS,
                         BRAIN_MAP)


def load_benchmarks() -> dict:
    """Load benchmarks file."""
    return load_json_dict(BENCHMARKS_FILE)


def find_completed_benchmarks(data: dict) -> list:
    """Find benchmarks that have outcomes but haven't been synthesized."""
    completed = []
    for bm in data.get("benchmarks", []):
        if bm.get("outcome") and not bm.get("synthesized"):
            completed.append(bm)
    return completed


def benchmark_to_evidence(bm: dict) -> dict:
    """Convert a benchmark outcome to an evidence item."""
    outcome = bm.get("outcome", {})
    result = outcome.get("result", "unknown")
    now = datetime.now(timezone.utc).isoformat()

    evidence = {
        "evidence": f"Benchmark {bm['id']}: {bm.get('description', '')}",
        "type": "win" if result == "achieved" else "fail",
        "source": f"benchmark_tracker/{bm['id']}",
        "date": now,
        "confidence": 0.9 if result == "achieved" else 0.85,
        "pattern": f"benchmark_{result}",
        "tags": ["benchmark", result, bm.get("id", "")],
        "benchmark_id": bm["id"],
        "criteria": bm.get("criteria", ""),
    }

    if result == "achieved":
        evidence["lesson"] = f"Successfully achieved: {bm.get('criteria', '')}"
        if outcome.get("notes"):
            evidence["lesson"] += f". Notes: {outcome['notes']}"
    else:
        evidence["lesson"] = f"Failed to achieve: {bm.get('criteria', '')}"
        if outcome.get("reason"):
            evidence["lesson"] += f". Reason: {outcome['reason']}"

    return evidence


def determine_evidence_file(bm: dict) -> str:
    """Determine which evidence file to append to."""
    desc = bm.get("description", "").lower()
    domain_keywords = {
        "translation": ["translat", "language", "text"],
        "tts": ["voice", "speech", "tts", "audio"],
        "ui": ["ui", "keyboard", "button", "interface"],
        "detection": ["detect", "identify", "classify"],
        "handler": ["handler", "command", "callback"],
    }
    for domain, keywords in domain_keywords.items():
        for kw in keywords:
            if kw in desc:
                return f"{domain}_learnings.json"
    return "benchmark_outcomes.json"


def write_evidence(evidence: dict, evidence_file: str):
    """Append evidence to the appropriate file."""
    learnings_dir = EVIDENCE_DIR / "Learnings"
    learnings_dir.mkdir(parents=True, exist_ok=True)
    path = learnings_dir / evidence_file
    items = load_json(path)
    if not isinstance(items, list):
        items = []
    items.append(evidence)
    save_json(path, items)
    print(f"  [EVIDENCE] Written to {evidence_file}")

# update_brain_map, update_growth_metrics, mark_synthesized, synthesize_* extracted
# to benchmark_synthesizer_ops.py and benchmark_synthesizer_main.py for Law 7.