from django.shortcuts import render, redirect
from .models import SimulationResult
from .risk_engine import RiskEngine
import json

def index(request):
    """Main dashboard showing the latest analysis and a list of historical runs."""
    latest = SimulationResult.objects.order_by('-created_at').first()
    history = SimulationResult.objects.order_by('-created_at')[1:10]
    
    context = {
        'latest': latest,
        'history': history,
        'status': 'Ready'
    }
    return render(request, 'core/index.html', context)

def run_simulation(request):
    """Executes the risk engine and stores the result."""
    if request.method == 'POST':
        try:
            engine = RiskEngine()
            results = engine.run_simulation()
            
            # Save to DB
            sim = SimulationResult.objects.create(
                expected_low=results['expected_low'],
                worst_case_5th=results['worst_case_5th'],
                drawdown_prob=results['drawdown_prob'],
                bias=results['bias'],
                take_profit=results['tp'],
                stop_loss=results['sl'],
                sentiment_score=results['sentiment'],
                regime=results['regime'],
                summary=f"Analysis for {engine.symbol} completed."
            )
            return redirect('index')
        except Exception as e:
            # For simplicity, pass error back to index
            return render(request, 'core/index.html', {'error': str(e), 'status': 'Error'})
            
    return redirect('index')