#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Benchmark lifecycle operations: create, achieve, fail, decay, archive.

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

from datetime import datetime, timezone

from pulse.admin.benchmarks.benchmark_tracker import (
    load_benchmarks, save_benchmarks, compute_salience, update_counters,
)


def create_benchmark(description: str, criteria: str, want_id: str = None) -> dict:
    """Create a new benchmark."""
    from pulse.admin.benchmarks.benchmark_tracker import next_id
    data = load_benchmarks()
    bm_id = next_id(data)
    now = datetime.now(timezone.utc).isoformat()
    benchmark = {
        "id": bm_id, "description": description, "criteria": criteria,
        "status": "active", "created": now, "updated": now,
        "salience": 1.0, "want_id": want_id, "outcome": None
    }
    data.setdefault("benchmarks", []).append(benchmark)
    update_counters(data)
    save_benchmarks(data)
    print(f"  [CREATED] {bm_id}: {description}")
    return benchmark


def achieve_benchmark(bm_id: str, notes: str = "") -> bool:
    """Mark benchmark as achieved."""
    data = load_benchmarks()
    for bm in data.get("benchmarks", []):
        if bm["id"] == bm_id and bm["status"] == "active":
            bm["status"] = "achieved"
            bm["updated"] = datetime.now(timezone.utc).isoformat()
            bm["outcome"] = {"result": "achieved", "notes": notes,
                             "date": datetime.now(timezone.utc).isoformat()}
            update_counters(data)
            save_benchmarks(data)
            print(f"  [ACHIEVED] {bm_id}: {bm['description']}")
            return True
    print(f"  [ERROR] {bm_id} not found or not active")
    return False


def fail_benchmark(bm_id: str, reason: str = "") -> bool:
    """Mark benchmark as failed."""
    data = load_benchmarks()
    for bm in data.get("benchmarks", []):
        if bm["id"] == bm_id and bm["status"] == "active":
            bm["status"] = "failed"
            bm["updated"] = datetime.now(timezone.utc).isoformat()
            bm["outcome"] = {"result": "failed", "reason": reason,
                             "date": datetime.now(timezone.utc).isoformat()}
            update_counters(data)
            save_benchmarks(data)
            print(f"  [FAILED] {bm_id}: {reason}")
            return True
    print(f"  [ERROR] {bm_id} not found or not active")
    return False


def apply_decay() -> list:
    """Apply salience decay to all active benchmarks."""
    data = load_benchmarks()
    decayed = []
    for bm in data.get("benchmarks", []):
        old_sal = bm.get("salience", 1.0)
        new_sal = compute_salience(bm.get("created", ""))
        if new_sal != old_sal:
            bm["salience"] = new_sal
            decayed.append({"id": bm["id"], "old": old_sal, "new": new_sal,
                            "description": bm["description"][:60]})
    if decayed:
        save_benchmarks(data)
    return decayed


def archive_stale() -> list:
    """Move benchmarks below salience threshold to archive."""
    from pulse.core.brain_utils import load_config
    config = load_config()
    threshold = config.get("decay", {}).get("benchmark_archive_threshold", 0.1)
    data = load_benchmarks()
    archived, remaining = [], []
    for bm in data.get("benchmarks", []):
        sal = compute_salience(bm.get("created", ""))
        bm["salience"] = sal
        if sal < threshold and bm.get("status") != "active":
            bm["archived_date"] = datetime.now(timezone.utc).isoformat()
            data.setdefault("archived", []).append(bm)
            archived.append({"id": bm["id"], "salience": sal,
                             "description": bm["description"][:60]})
            print(f"  [ARCHIVED] {bm['id']} (salience={sal:.4f})")
        else:
            remaining.append(bm)
    if archived:
        data["benchmarks"] = remaining
        update_counters(data)
        save_benchmarks(data)
    return archived
