#!/usr/bin/env python3
"""Scenario simulation: Propagate economic shocks through the causal DAG.

Demonstrates:
1. Built-in CCAR scenario simulation.
2. Custom scenario definition.
3. Monte Carlo stress testing.
"""

from orxaq.intelligence.simulator import (
    BUILT_IN_SCENARIOS,
    Scenario,
    ScenarioSimulator,
    Shock,
)
from orxaq.orchestration.integration import OrxaqEngine

engine = OrxaqEngine()
engine.load_credit_ontology()
sim = ScenarioSimulator(engine.world_dag, seed=42)

# --- Built-in adverse scenario ---
print("=== Built-in Adverse Scenario ===")
result = sim.simulate(BUILT_IN_SCENARIOS["adverse"])
print(f"Affected variables: {result.total_affected}")
print(f"Max propagation depth: {result.max_depth}")
print(f"Impact score: {result.impact_score:.4f}")
for step in result.steps[:5]:
    print(f"  [{step.depth}] {step.variable}: {step.original_value:.4f} -> {step.new_value:.4f}")

# --- Custom scenario ---
print("\n=== Custom Rate Shock ===")
custom = Scenario(
    name="rate_shock_300bp",
    description="300bp interest rate increase",
    severity="high",
    shocks=[
        Shock(variable="interest_rate", value=0.03, shock_type="delta"),
    ],
)
result = sim.simulate(custom)
print(f"Impact score: {result.impact_score:.4f}")
for step in result.steps:
    src = f" (from {', '.join(step.source_variables)})" if step.source_variables else " (shock)"
    print(f"  [{step.depth}] {step.variable}: delta={step.delta:+.4f}{src}")

# --- Monte Carlo ---
print("\n=== Monte Carlo (100 runs) ===")
mc = sim.monte_carlo(BUILT_IN_SCENARIOS["severely_adverse"], n_simulations=100)
mean = mc["impact_score_mean"]
p5, p95 = mc["impact_score_p5"], mc["impact_score_p95"]
print(f"Impact score: {mean:.4f} [{p5:.4f}, {p95:.4f}]")
for var_id, stats in sorted(mc["variable_stats"].items())[:5]:
    print(
        f"  {var_id}: mean_delta={stats['mean_delta']:.6f} [{stats['p5']:.6f}, {stats['p95']:.6f}]"
    )
