#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain Recommender CLI and recommendation pipeline.

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

import json
import sys
from datetime import datetime, timezone


def generate_recommendation(want: str, config: dict = None) -> dict:
    """Full recommendation pipeline: search -> analyze -> recommend."""
    from pulse.core.brain_utils import load_config
    from pulse.brain.brain_search import brain_search
    from pulse.admin.brain_ops.brain_recommender import (  # lazy — avoids circular
        extract_warnings, extract_approaches, extract_context,
        detect_contradictions, compute_confidence,
    )
    if config is None:
        config = load_config()
    search_results = brain_search(want, config)
    warnings = extract_warnings(search_results)
    approaches = extract_approaches(search_results)
    context = extract_context(search_results)
    contradictions = detect_contradictions(warnings, approaches)
    evidence_count = len(search_results.get("results", {}).get("evidence", []))
    confidence = compute_confidence(approaches, warnings, evidence_count)
    recommendation = {
        "want": want,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "confidence": confidence,
        "search_stats": {
            "total_results": search_results.get("total_results", 0),
            "elapsed_ms": search_results.get("elapsed_ms", 0)
        },
        "approach": None, "warnings": warnings[:5],
        "context": context[:3], "contradictions": contradictions,
        "evidence_depth": evidence_count
    }
    if approaches:
        best = approaches[0]
        recommendation["approach"] = {
            "summary": best.get("text", "")[:200], "type": best.get("type", "unknown"),
            "salience": best.get("salience", 0), "confidence": best.get("confidence", 0.5),
            "alternatives": len(approaches) - 1
        }
    return recommendation


def main():
    if len(sys.argv) < 2:
        print("Usage: brain_recommender.py \"want description\" [--json]")
        return
    want = sys.argv[1]
    as_json = "--json" in sys.argv
    print(f"=== Brain Recommender V43.12: \"{want}\" ===")
    rec = generate_recommendation(want)
    if as_json:
        print(json.dumps(rec, indent=2))
    else:
        print(f"  Confidence: {rec['confidence']:.0%}")
        print(f"  Search: {rec['search_stats']['total_results']} results "
              f"in {rec['search_stats']['elapsed_ms']}ms")
        if rec["approach"]:
            a = rec["approach"]
            print(f"\n  RECOMMENDED APPROACH ({a['type']}, salience={a['salience']:.3f}):")
            print(f"    {a['summary'][:120]}")
            if a["alternatives"]:
                print(f"    ({a['alternatives']} alternative(s) found)")
        else:
            print("\n  No proven approach found. Proceed with caution.")
        if rec["warnings"]:
            print(f"\n  WARNINGS ({len(rec['warnings'])}):")
            for w in rec["warnings"]:
                print(f"    [{w['severity'].upper()}] {w['title']}: {w['text'][:80]}")
        if rec["contradictions"]:
            print(f"\n  CONTRADICTIONS ({len(rec['contradictions'])}):")
            for c in rec["contradictions"]:
                print(f"    {c['warning'][:40]} <-> {c['approach'][:40]}")
        if rec["context"]:
            print(f"\n  CONTEXT ({len(rec['context'])} domains):")
            for ctx in rec["context"]:
                print(f"    {ctx['file']}: {ctx['text'][:80]}")


if __name__ == "__main__":
    main()
