"""Test neuronlens analyze_reasoning function."""
import os
from pathlib import Path
import neuronlens

env_path = Path(__file__).parent.parent / ".env"
if env_path.exists():
    try:
        from dotenv import load_dotenv
        load_dotenv(env_path, override=True)
    except ImportError:
        pass

engine = neuronlens.Engine(api_key=os.getenv("API_KEY") or os.getenv("NEURONLENS_API_KEY"))

print("=== Testing NeuronLens Reasoning Analysis ===\n")

# Use ngrok URL (from config.json or default)
result = engine.analyze_reasoning("What is 2+2? Show your reasoning.")

# Display CoT and final answer
if result.get('cot_text'):
    print(f"CoT: {result['cot_text'][:200]}...")
if result.get('final_answer'):
    print(f"Final Answer: {result['final_answer']}")

# Display bucket scores for prompt/CoT/final
buckets = result.get('buckets', {})
for section in ['prompt', 'cot', 'final']:
    if buckets.get(section):
        top = sorted(buckets[section].items(), key=lambda x: x[1], reverse=True)[:3]
        print(f"{section.capitalize()} buckets: {dict(top)}")

# Display faithfulness and metrics
faithfulness = result.get('faithfulness', {})
print(f"Faithfulness: {faithfulness.get('score', 0):.3f} ({faithfulness.get('level', 'N/A')})")
metrics = result.get('metrics', {})
if metrics:
    print(f"Metrics: coverage={metrics.get('feature_coverage', 0):.3f}, purity={metrics.get('purity', 0):.3f}")

engine.unload_all_models()
print("\n=== Reasoning test passed ===")
