-- View: prediction_accuracy
-- Joins prediction_vs_outcome with trade_signals and market_bars to provide
-- a comprehensive prediction accuracy scorecard.
-- Requirements: 10.1, 10.2, 10.3, 10.4
-- Design ref: Section 9.2 (prediction confidence vs realized move)

CREATE OR REPLACE VIEW lakehouse.stonks.prediction_accuracy AS
SELECT
    pvo.recommendation_id,
    pvo.ticker,
    pvo.predicted_action,
    pvo.predicted_confidence,
    pvo.actual_move_pct,
    pvo.outcome,
    pvo.horizon_days,
    pvo.predicted_at,
    pvo.evaluated_at,
    pvo.model_version,
    ts.trend_direction,
    ts.trend_strength,
    ts.contradiction_score,
    ts.dominant_catalysts,
    -- Confidence bucket for dashboard grouping
    CASE
        WHEN pvo.predicted_confidence >= 0.8 THEN 'high'
        WHEN pvo.predicted_confidence >= 0.5 THEN 'medium'
        ELSE 'low'
    END AS confidence_bucket,
    -- Direction correctness: did the predicted action match the actual move?
    CASE
        WHEN pvo.predicted_action = 'buy' AND pvo.actual_move_pct > 0 THEN true
        WHEN pvo.predicted_action = 'sell' AND pvo.actual_move_pct < 0 THEN true
        WHEN pvo.predicted_action IN ('hold', 'watch') THEN NULL
        ELSE false
    END AS direction_correct,
    -- Magnitude of prediction error
    ABS(pvo.actual_move_pct) AS abs_move_pct,
    pvo.dt
FROM
    lakehouse.stonks.prediction_vs_outcome pvo
LEFT JOIN
    lakehouse.stonks.trade_signals ts
    ON pvo.recommendation_id = ts.recommendation_id
    AND pvo.dt = ts.dt;
