-- K-ArtSell Aegis Gate 5: Shadow Run Monitoring
-- Job 893: 252+ trading days validation
-- Usage: psql -h localhost -U kartsell -d kartsell -f monitor-shadow-run.sql

-- Get overall job status
SELECT
    job_id,
    correlation_id,
    status,
    created_at,
    updated_at,
    EXTRACT(EPOCH FROM (updated_at - created_at)) / 3600 as duration_hours,
    ROUND(100.0 * EXTRACT(EPOCH FROM (updated_at - created_at)) /
          (252 * 24), 2) as estimated_progress_percent
FROM shared.outbox_jobs
WHERE job_id = '00000000-0000-0000-0000-000000000893'
LIMIT 1;

-- Shadow run execution phases
SELECT
    phase_id,
    phase_name,
    started_at,
    completed_at,
    status,
    EXTRACT(EPOCH FROM (COALESCE(completed_at, now()) - started_at)) / 3600 as phase_duration_hours,
    CASE
        WHEN completed_at IS NOT NULL THEN 'COMPLETED'
        WHEN started_at IS NOT NULL THEN 'IN PROGRESS'
        ELSE 'PENDING'
    END as current_status
FROM model_operations.shadow_run_phases
WHERE shadow_run_id = '00000000-0000-0000-0000-000000000893'
ORDER BY phase_sequence;

-- Data validation metrics
SELECT
    validation_type,
    COUNT(*) as total_validations,
    SUM(CASE WHEN status = 'passed' THEN 1 ELSE 0 END) as passed,
    SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed,
    SUM(CASE WHEN status = 'warning' THEN 1 ELSE 0 END) as warnings,
    ROUND(100.0 * SUM(CASE WHEN status = 'passed' THEN 1 ELSE 0 END) /
          NULLIF(COUNT(*), 0), 2) as success_rate_percent
FROM model_operations.shadow_run_validations
WHERE shadow_run_id = '00000000-0000-0000-0000-000000000893'
GROUP BY validation_type
ORDER BY validation_type;

-- Performance metrics (Sharpe, PBO, etc.)
SELECT
    metric_name,
    metric_value,
    lower_bound,
    upper_bound,
    CASE
        WHEN metric_value::numeric >= lower_bound::numeric AND
             metric_value::numeric <= upper_bound::numeric THEN '✅ PASS'
        ELSE '❌ FAIL'
    END as status,
    measurement_timestamp
FROM model_operations.shadow_run_metrics
WHERE shadow_run_id = '00000000-0000-0000-0000-000000000893'
ORDER BY measurement_timestamp DESC
LIMIT 20;

-- Recent log entries
SELECT
    timestamp,
    log_level,
    message,
    EXTRACT(EPOCH FROM (now() - timestamp)) / 60 as minutes_ago
FROM model_operations.shadow_run_logs
WHERE shadow_run_id = '00000000-0000-0000-0000-000000000893'
ORDER BY timestamp DESC
LIMIT 50;

-- Calculate estimated completion
WITH job_start AS (
    SELECT created_at FROM shared.outbox_jobs
    WHERE job_id = '00000000-0000-0000-0000-000000000893'
)
SELECT
    CONCAT('Shadow Run Gate 5: ',
        EXTRACT(DAY FROM (now() - job_start.created_at))::text, ' days elapsed') as elapsed,
    'Estimated completion: 50-90 days from start' as estimate,
    job_start.created_at as started_at,
    (job_start.created_at + INTERVAL '90 days') as max_completion_date
FROM job_start;
