"""
Example usage of neuronlens package.

This file demonstrates how to use the neuronlens package.
Run this after installing: pip install -e .
"""
import neuronlens

def example_with_api_key():
    """Example using API key (required)"""
    print("=" * 60)
    print("Example: Using API Key (Required)")
    print("=" * 60)
    
    # API key is required - get from environment or provide directly
    import os
    api_key = os.getenv("NEURONLENS_API_KEY") or os.getenv("API_KEY")
    if not api_key:
        print("Error: API key required. Set NEURONLENS_API_KEY environment variable.")
        return
    
    try:
        engine = neuronlens.Engine(api_key=api_key)
        
        # Example: Sentiment Analysis
        print("\n1. Sentiment Analysis:")
        result = engine.analyze_sentiment("Strong quarterly earnings exceeded expectations", top_n=5)
        print(f"   Sentiment: {result.get('sentiment', {}).get('predicted_label', 'N/A')}")
        print(f"   Confidence: {result.get('sentiment', {}).get('confidence', 0):.3f}")
        
        # Example: Agent Analysis
        print("\n2. Agent Analysis:")
        result = engine.analyze_agent("Get Tesla stock price")
        print(f"   Alignment Status: {result.get('alignment_status', 'N/A')}")
        print(f"   Tool Called: {result.get('tool_called', 'N/A')}")
        
        # Example: Trading Analysis
        print("\n3. Trading Analysis:")
        result = engine.analyze_trading("Apple reported strong earnings", "AAPL")
        print(f"   Signals extracted: {len(result.get('signals', []))}")
        
        # Example: Reasoning Analysis
        print("\n4. Reasoning Analysis:")
        result = engine.analyze_reasoning("What is 2+2? Show reasoning.", max_new_tokens=100)
        print(f"   Features: {len(result.get('features', []))}")
        
        # Example: Hallucination Detection
        print("\n5. Hallucination Detection:")
        result = engine.analyze_hallucination("Write a summary about Apple", max_tokens=50)
        print(f"   Tokens analyzed: {len(result.get('token_details', []))}")
        
        # Example: Search Features
        print("\n6. Search Features:")
        features = engine.search_features("financial analysis", k=5, layer=16)
        print(f"   Features found: {len(features)}")
        
        # Example: Steer Features
        print("\n7. Steer Features:")
        if features:
            steered = engine.steer_features(
                "What is the market outlook?",
                [{"id": features[0].get('feature_id', 'f_100'), "magnitude": 0.5}]
            )
            print(f"   Success: {steered.get('success', False)}")
        
        # Example: Common Functions
        print("\n8. Common Functions:")
        status = engine.model_cache_status()
        print(f"   Cache status: {status.get('loaded_models', [])}")
        
    except ValueError as e:
        print(f"Configuration error: {e}")
    except Exception as e:
        print(f"Error: {e}")


def example_environment_variables():
    """Example using environment variables"""
    print("\n" + "=" * 60)
    print("Example: Using Environment Variables")
    print("=" * 60)
    
    import os
    
    # Set environment variables (in real usage, set these in your shell)
    # os.environ['NEURONLENS_API_KEY'] = "nlive_your_key"
    # os.environ['NEURONLENS_API_URL'] = "https://your-ngrok-url.ngrok-free.dev"
    
    # Initialize - automatically picks up from environment
    try:
        engine = neuronlens.Engine()
        print(f"API URL: {engine.api_url}")
        print(f"Has API Key: {engine.api_key is not None}")
    except ValueError as e:
        print(f"Error: {e}")
        print("   Set NEURONLENS_API_KEY environment variable to use this mode")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    print("NeuronLens Package - Usage Examples\n")
    
    # Run examples
    example_with_api_key()
    example_environment_variables()
    
    print("\n" + "=" * 60)
    print("For more examples, see neuronlens/README.md")
    print("=" * 60)
