#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Benchmark synthesis operations: brain map updates, mark synthesized, full pipeline.

Split from benchmark_synthesizer.py for Law 7 compliance.
"""
from __future__ import annotations

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

from pulse.core.brain_utils import save_json, BRAIN_MAP, GROWTH_METRICS, BENCHMARKS_FILE
from pulse.admin.benchmarks.benchmark_synthesizer import (
    load_benchmarks, benchmark_to_evidence, determine_evidence_file, write_evidence,
)


def update_brain_map(bm_id: str, evidence_file: str):
    """Update brain map with benchmark->evidence connection."""
    from pulse.core.brain_utils import load_json_dict
    brain_map = load_json_dict(BRAIN_MAP)
    brain_map.setdefault("benchmark_connections", {})
    brain_map["benchmark_connections"][bm_id] = {
        "evidence_file": f"evidence/{evidence_file}",
        "date": date.today().isoformat()
    }
    save_json(BRAIN_MAP, brain_map)


def update_growth_metrics(bm_id: str, result: str):
    """Update growth metrics with benchmark synthesis."""
    from pulse.core.brain_utils import load_json_dict
    metrics = load_json_dict(GROWTH_METRICS)
    benchmarks = metrics.setdefault("benchmark_synthesis", [])
    benchmarks.append({
        "benchmark_id": bm_id, "result": result,
        "date": datetime.now(timezone.utc).isoformat()
    })
    if len(benchmarks) > 100:
        metrics["benchmark_synthesis"] = benchmarks[-50:]
    save_json(GROWTH_METRICS, metrics)


def mark_synthesized(data: dict, bm_id: str):
    """Mark benchmark as synthesized to prevent re-processing."""
    for bm in data.get("benchmarks", []):
        if bm["id"] == bm_id:
            bm["synthesized"] = True
            bm["synthesized_date"] = datetime.now(timezone.utc).isoformat()
            break


def synthesize_benchmark(bm: dict, data: dict, dry_run: bool = False) -> dict:
    """Full synthesis pipeline for one benchmark."""
    evidence = benchmark_to_evidence(bm)
    evidence_file = determine_evidence_file(bm)
    result = bm.get("outcome", {}).get("result", "unknown")
    report = {
        "benchmark_id": bm["id"], "result": result,
        "evidence_file": evidence_file, "evidence_type": evidence["type"],
        "lesson": evidence.get("lesson", "")
    }
    if not dry_run:
        write_evidence(evidence, evidence_file)
        update_brain_map(bm["id"], evidence_file)
        update_growth_metrics(bm["id"], result)
        mark_synthesized(data, bm["id"])
        save_json(BENCHMARKS_FILE, data)
        print(f"  [SYNTHESIZED] {bm['id']} -> {evidence_file} ({result})")
    else:
        print(f"  [DRY-RUN] {bm['id']} -> {evidence_file} ({result})")
    return report


def synthesize_one(bm_id: str, dry_run: bool = False) -> dict:
    """Synthesize a specific benchmark by ID."""
    data = load_benchmarks()
    for bm in data.get("benchmarks", []):
        if bm["id"] == bm_id:
            if not bm.get("outcome"):
                print(f"  [ERROR] {bm_id} has no outcome yet")
                return {}
            if bm.get("synthesized"):
                print(f"  [SKIP] {bm_id} already synthesized")
                return {}
            return synthesize_benchmark(bm, data, dry_run)
    print(f"  [ERROR] {bm_id} not found")
    return {}
