#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Benchmark Tracker CLI and list command.

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

import sys

from pulse.admin.benchmarks.benchmark_tracker import load_benchmarks, compute_salience
from pulse.admin.benchmarks.benchmark_tracker_ops import (
    create_benchmark, achieve_benchmark, fail_benchmark, apply_decay, archive_stale,
)


def list_benchmarks():
    """Display all benchmarks with current salience."""
    data = load_benchmarks()
    benchmarks = data.get("benchmarks", [])
    if not benchmarks:
        print("  No active benchmarks.")
        return
    print(f"  Total: {len(benchmarks)} benchmarks")
    for bm in benchmarks:
        sal = compute_salience(bm.get("created", ""))
        status = bm.get("status", "unknown").upper()
        desc = bm.get("description", "")[:60]
        print(f"  [{status}] {bm['id']} (salience={sal:.3f}): {desc}")


def main():
    print("=== Benchmark Tracker V43.12 ===")

    if "--list" in sys.argv:
        list_benchmarks()
        return

    if "--create" in sys.argv:
        idx = sys.argv.index("--create")
        desc = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else "Unnamed"
        criteria = ""
        if "--criteria" in sys.argv:
            ci = sys.argv.index("--criteria")
            criteria = sys.argv[ci + 1] if ci + 1 < len(sys.argv) else ""
        want_id = None
        if "--want" in sys.argv:
            wi = sys.argv.index("--want")
            want_id = sys.argv[wi + 1] if wi + 1 < len(sys.argv) else None
        create_benchmark(desc, criteria, want_id)
        return

    if "--achieve" in sys.argv:
        idx = sys.argv.index("--achieve")
        bm_id = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        notes = ""
        if "--notes" in sys.argv:
            ni = sys.argv.index("--notes")
            notes = sys.argv[ni + 1] if ni + 1 < len(sys.argv) else ""
        achieve_benchmark(bm_id, notes)
        return

    if "--fail" in sys.argv:
        idx = sys.argv.index("--fail")
        bm_id = sys.argv[idx + 1] if idx + 1 < len(sys.argv) else ""
        reason = ""
        if "--reason" in sys.argv:
            ri = sys.argv.index("--reason")
            reason = sys.argv[ri + 1] if ri + 1 < len(sys.argv) else ""
        fail_benchmark(bm_id, reason)
        return

    if "--decay" in sys.argv:
        decayed = apply_decay()
        print(f"  Decayed: {len(decayed)} benchmarks")
        for d in decayed:
            print(f"    {d['id']}: {d['old']:.3f} -> {d['new']:.3f}")
        return

    if "--archive" in sys.argv:
        archived = archive_stale()
        print(f"  Archived: {len(archived)} benchmarks")
        return

    print("  Usage: --list | --create | --achieve | --fail | --decay | --archive")


if __name__ == "__main__":
    main()
