# -- DASHBOARD SECTION: start

overview_page = app.create_page('Executive Overview')

col1 = overview_page.create_section('Global Energy Trading Performance & Risk Intelligence', 1)
col1.text_widget(html='''
<h1>Global Energy Trading Performance & Risk Intelligence Dashboard</h1>
<h2>Overview</h2>
<p>This dashboard provides comprehensive performance and risk analytics for energy trading operations across all commodities (Crude Oil, Natural Gas, LNG, Refined Products), trading desks, and regions. It enables explainable P&L attribution, risk utilization monitoring, and proactive breach detection.</p>

<h3>Key Features</h3>
<p><strong>Interactive Variables:</strong> Adjust the "Risk Utilization Threshold" to modify warning levels across all risk widgets. Set "Analysis Start Date" and "Analysis End Date" to define your analysis period. Modify "Stress Scenario Multiplier" to simulate different stress conditions.</p>

<p><strong>Dashboard Navigation:</strong> Use the Executive Overview for high-level KPIs, P&L Attribution for detailed performance analysis, Risk Management for monitoring desk-level risk metrics, and Trade Analysis for granular trade-level insights.</p>
''')

col1, col2, col3 = overview_page.create_section('Portfolio Performance Summary', 3)

col1.indicator_chart(
    title='Total P&L ($)',
    indicator='total_pnl',
    aggregation='SUM',
    source=model,
)

col2.indicator_chart(
    title='Average Risk Utilization (%)',
    indicator='risk_utilization_pct',
    aggregation='AVERAGE',
    source=model,
)

col3.indicator_chart(
    title='Risk Breaches',
    indicator='is_risk_breach',
    aggregation='SUM',
    source=model,
)

col1, col2 = overview_page.create_section('P&L and Risk Overview', 2)

col1.bar_chart(
    title='Total P&L by Desk ($)',
    x='desk',
    y='total_pnl',
    aggregation='SUM',
    show_values=True,
    source=model,
)

col2.bar_chart(
    title='Risk Utilization by Desk (%)',
    x='desk',
    y='risk_utilization_pct',
    aggregation='AVERAGE',
    show_values=True,
    source=model,
)

col1, col2 = overview_page.create_section('Commodity and Regional Analysis', 2)

col1.pie_chart(
    title='P&L by Commodity Type ($)',
    labels='commodity_type',
    values='total_pnl',
    aggregation='SUM',
    show_values=True,
    show_labels=True,
    source=model,
)

col2.pie_chart(
    title='Trade Volume by Region',
    labels='region',
    values='trade_id',
    aggregation='COUNT',
    show_values=True,
    show_labels=True,
    source=model,
)


pnl_page = app.create_page('P&L Attribution')

col1 = pnl_page.create_section('P&L Attribution Analysis', 1)
col1.text_widget(html='''
<h1>P&L Attribution & Performance Analysis</h1>
<h2>Understanding P&L Drivers</h2>
<p>This page provides detailed decomposition of profit and loss across multiple dimensions. The P&L Attribution framework breaks down daily performance into constituent drivers: price movements (price_effect), volume adjustments (volume_effect), FX fluctuations (fx_effect), basis differentials (basis_effect), and unexplained variance.</p>

<h3>How Variables Impact This Page</h3>
<p>The "Analysis Start Date" and "Analysis End Date" variables filter all P&L metrics to your selected time period. The "PnL Threshold for Alerts" variable determines which trades are flagged as significant losses in the loss-making trades analysis.</p>

<p>Use the charts below to identify which desks, commodities, and trade types are driving portfolio performance, and understand the specific factors contributing to P&L outcomes.</p>
''')

col1, col2 = pnl_page.create_section('P&L Attribution Breakdown', 2)

col1.bar_chart(
    title='P&L Attribution by Effect Type ($)',
    x='desk',
    y=('total_price_effect', 'total_fx_effect', 'total_basis_effect', 'total_unexplained_pnl'),
    aggregation=('SUM', 'SUM', 'SUM', 'SUM'),
    show_values=False,
    source=model,
)

col2.line_chart(
    title='Cumulative P&L Over Time ($)',
    x='trade_date',
    y='total_pnl',
    aggregation='SUM',
    time_sampling='DAY',
    show_values=False,
    area=True,
    source=model,
)

col1, col2 = pnl_page.create_section('Performance Metrics', 2)

col1.bar_chart(
    title='P&L/VaR Efficiency by Desk',
    x='desk',
    y='pnl_var_efficiency',
    aggregation='AVERAGE',
    show_values=True,
    source=model,
)

col2.scatter_chart(
    title='P&L vs Market Volatility',
    granularity='commodity',
    x='avg_market_volatility',
    aggregation_x='AVERAGE',
    y='total_pnl',
    aggregation_y='SUM',
    color='region',
    aggregation_color='COUNT',
    source=model,
)

col1, col2 = pnl_page.create_section('Trade Performance Analysis', 2)

col1.bar_chart(
    title='P&L by Instrument Type ($)',
    x='instrument_type',
    y='total_pnl',
    aggregation='SUM',
    show_values=True,
    source=model,
)

col2.bar_chart(
    title='Top 10 Loss-Making Trades ($)',
    x='trade_id',
    y='total_pnl',
    aggregation='SUM',
    show_values=True,
    source=model,
)


risk_page = app.create_page('Risk Management')

col1 = risk_page.create_section('Risk Management & Monitoring', 1)
col1.text_widget(html='''
<h1>Risk Management Dashboard</h1>
<h2>Proactive Risk Monitoring</h2>
<p>This page provides comprehensive risk monitoring across all trading desks, enabling early detection of limit breaches and risk warnings. The dashboard tracks Value-at-Risk (VaR), stress scenarios, exposure levels, and limit utilization in real-time.</p>

<h3>Variable-Driven Risk Alerts</h3>
<p>The "Risk Utilization Threshold" variable (default 80%) determines when desks are flagged with warnings. Any desk exceeding this threshold percentage will appear in risk warning charts. The "Stress Scenario Multiplier" variable allows you to model stressed market conditions and project potential breaches under adverse scenarios.</p>

<p>Risk Status categories: <strong>Normal</strong> (below threshold), <strong>Warning</strong> (≥threshold but no breach), <strong>Breach</strong> (VaR exceeds limit). Monitor the stressed risk metrics to anticipate potential breaches before they occur.</p>
''')

col1, col2, col3 = risk_page.create_section('Risk KPIs', 3)

col1.indicator_chart(
    title='Average VaR ($)',
    indicator='avg_var',
    aggregation='AVERAGE',
    source=model,
)

col2.indicator_chart(
    title='Desks at Risk Warning',
    indicator='is_risk_warning',
    aggregation='SUM',
    source=model,
)

col3.indicator_chart(
    title='Total Breach Days',
    indicator='total_breach_days',
    aggregation='SUM',
    source=model,
)

col1, col2 = risk_page.create_section('Risk Utilization Analysis', 2)

col1.bar_chart(
    title='Current vs Stressed Risk Utilization by Desk (%)',
    x='desk',
    y=('risk_utilization_pct', 'stressed_risk_utilization_pct'),
    aggregation=('AVERAGE', 'AVERAGE'),
    show_values=True,
    show_totals=False,
    source=model,
)

col2.bar_chart(
    title='Risk Status Distribution by Desk',
    x='desk',
    y='risk_status',
    aggregation='COUNT',
    color='risk_status',
    show_values=True,
    source=model,
)

col1, col2 = risk_page.create_section('VaR and Exposure Metrics', 2)

col1.scatter_chart(
    title='VaR vs Exposure by Desk',
    granularity='desk',
    x='avg_exposure',
    aggregation_x='AVERAGE',
    y='avg_var',
    aggregation_y='AVERAGE',
    color='region',
    aggregation_color='COUNT',
    source=model,
)

col2.bar_chart(
    title='Stress-to-VaR Ratio by Desk',
    x='desk',
    y='stress_to_var_ratio',
    aggregation='AVERAGE',
    show_values=True,
    source=model,
)

col1, col2 = risk_page.create_section('Breach Detection', 2)

col1.bar_chart(
    title='Breach Days by Desk',
    x='desk',
    y='total_breach_days',
    aggregation='SUM',
    show_values=True,
    source=model,
)

col2.bar_chart(
    title='Stressed Breach Probability',
    x='desk',
    y='is_stressed_breach',
    aggregation='SUM',
    show_values=True,
    source=model,
)


trade_page = app.create_page('Trade Analysis')

col1 = trade_page.create_section('Granular Trade-Level Analysis', 1)
col1.text_widget(html='''
<h1>Trade-Level Intelligence</h1>
<h2>Deep Dive into Trading Activity</h2>
<p>This page enables detailed analysis of individual trades and trading patterns across the portfolio. Explore trade characteristics, counterparty exposures, market pricing dynamics, and instrument type distributions to identify opportunities and risks at the most granular level.</p>

<h3>Trade Filtering and Analysis</h3>
<p>The "Minimum Trade Size USD" variable filters trades by notional value, allowing you to focus on material positions. Use the date range variables to analyze specific periods. The charts below help identify large trades, problematic positions, and trading patterns that may require attention.</p>

<p>Pay particular attention to trades where entry price significantly deviates from average market prices, trades with high unexplained P&L percentages, and large physical vs paper trade imbalances that could indicate hedging gaps.</p>
''')

col1, col2 = trade_page.create_section('Trade Characteristics', 2)

col1.bar_chart(
    title='Trade Count by Counterparty',
    x='counterparty',
    y='trade_id',
    aggregation='COUNT',
    show_values=True,
    source=model,
)

col2.bar_chart(
    title='Average Trade Size by Commodity ($M)',
    x='commodity',
    y='trade_notional_value',
    aggregation='AVERAGE',
    show_values=True,
    source=model,
)

col1, col2 = trade_page.create_section('Physical vs Paper Analysis', 2)

col1.pie_chart(
    title='Trade Volume: Physical vs Paper',
    labels='instrument_type',
    values='trade_id',
    aggregation='COUNT',
    show_values=True,
    show_labels=True,
    doughnut=True,
    source=model,
)

col2.bar_chart(
    title='P&L by Physical vs Paper ($)',
    x='commodity',
    y='total_pnl',
    aggregation='SUM',
    color='instrument_type',
    show_values=False,
    source=model,
)

col1, col2 = trade_page.create_section('Market Pricing Analysis', 2)

col1.scatter_chart(
    title='Entry Price vs Market Price by Trade',
    granularity='trade_id',
    x='price',
    aggregation_x='AVERAGE',
    y='avg_market_price',
    aggregation_y='AVERAGE',
    color='commodity',
    aggregation_color='COUNT',
    source=model,
)

col2.bar_chart(
    title='Market Volatility by Commodity (%)',
    x='commodity',
    y='avg_market_volatility',
    aggregation='AVERAGE',
    show_values=True,
    source=model,
)

col1, col2 = trade_page.create_section('Large Trades and Loss Analysis', 2)

col1.bar_chart(
    title='Large Trades by Desk (Count)',
    x='desk',
    y='is_large_trade',
    aggregation='SUM',
    show_values=True,
    source=model,
)

col2.bar_chart(
    title='Large Loss Trades by Commodity',
    x='commodity',
    y='is_large_loss',
    aggregation='SUM',
    show_values=True,
    source=model,
)

# -- DASHBOARD SECTION: end
