-- Seed pre-built saved queries for the SQL Explorer
-- Add unique constraint on name to prevent duplicates on re-run
DO $$ BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'saved_queries_name_key') THEN
    ALTER TABLE saved_queries ADD CONSTRAINT saved_queries_name_key UNIQUE (name);
  END IF;
END $$;

INSERT INTO saved_queries (name, description, sql_text) VALUES
('Company Overview', 'All tracked companies with sector and status',
 'SELECT ticker, legal_name, sector, active, created_at FROM companies ORDER BY ticker'),

('Recent Recommendations', 'Latest buy/sell recommendations with confidence',
 'SELECT ticker, action, confidence, mode, risk_classification, generated_at FROM recommendations WHERE action IN (''buy'', ''sell'') ORDER BY generated_at DESC LIMIT 50'),

('High Confidence Buys', 'Buy recommendations with confidence >= 0.75',
 'SELECT ticker, confidence, mode, thesis, generated_at FROM recommendations WHERE action = ''buy'' AND confidence >= 0.75 ORDER BY confidence DESC LIMIT 50'),

('Trend Windows Summary', 'Current trend direction and strength by ticker',
 'SELECT entity_id AS ticker, "window", trend_direction, trend_strength, confidence FROM trend_windows ORDER BY trend_strength DESC LIMIT 100'),

('Market Prices', 'Latest close prices for tracked companies',
 'SELECT DISTINCT ON (ticker) ticker, (data->>''c'')::float AS close, (data->>''o'')::float AS open, (data->>''h'')::float AS high, (data->>''l'')::float AS low, (data->>''v'')::float AS volume, captured_at FROM market_snapshots WHERE snapshot_type = ''bar'' ORDER BY ticker, captured_at DESC'),

('Document Counts by Type', 'Count of documents by type and status',
 'SELECT document_type, status, count(*) FROM documents GROUP BY document_type, status ORDER BY document_type, count(*) DESC'),

('Global Events', 'Recent macro events with severity',
 'SELECT severity, LEFT(summary, 100) AS summary, event_types, affected_sectors, created_at FROM global_events ORDER BY created_at DESC LIMIT 30'),

('Trading Decisions', 'Recent trading engine decisions',
 'SELECT ticker, decision, skip_reason, computed_position_size, computed_share_quantity, risk_tier_at_decision, created_at FROM trading_decisions ORDER BY created_at DESC LIMIT 50'),

('Ingestion Health', 'Source ingestion run stats (last 24h)',
 'SELECT s.source_type, s.source_name, count(*) AS runs, count(*) FILTER (WHERE ir.status = ''completed'') AS completed, count(*) FILTER (WHERE ir.status = ''failed'') AS failed FROM ingestion_runs ir JOIN sources s ON ir.source_id = s.id WHERE ir.started_at > NOW() - INTERVAL ''24 hours'' GROUP BY s.source_type, s.source_name ORDER BY failed DESC, runs DESC'),

('Reserve Pool Ledger', 'Reserve pool transaction history',
 'SELECT amount, balance_after, trigger_type, notes, created_at FROM reserve_pool_ledger ORDER BY created_at DESC LIMIT 30'),

('Sector Exposure', 'Market value by sector from positions',
 'SELECT c.sector, count(*) AS positions, sum((ms.data->>''c'')::float) AS total_close_price FROM companies c JOIN market_snapshots ms ON c.ticker = ms.ticker WHERE ms.snapshot_type = ''bar'' GROUP BY c.sector ORDER BY total_close_price DESC'),

('Source Coverage Matrix', 'Active sources per company',
 'SELECT c.ticker, c.legal_name, count(*) FILTER (WHERE s.source_type = ''market_api'') AS market, count(*) FILTER (WHERE s.source_type = ''news_api'') AS news, count(*) FILTER (WHERE s.source_type = ''filings_api'') AS filings, count(*) AS total FROM companies c LEFT JOIN sources s ON c.id = s.company_id AND s.active = TRUE WHERE c.active = TRUE GROUP BY c.ticker, c.legal_name ORDER BY c.ticker'),

('Top Movers', 'Biggest price change vs previous day open',
 'SELECT DISTINCT ON (ticker) ticker, (data->>''c'')::numeric AS close, (data->>''o'')::numeric AS open, round(((data->>''c'')::numeric - (data->>''o'')::numeric) / NULLIF((data->>''o'')::numeric, 0) * 100, 2) AS change_pct FROM market_snapshots WHERE snapshot_type = ''bar'' AND (data->>''o'')::float > 0 ORDER BY ticker, captured_at DESC'),

('Companies with Close Price', 'All tracked companies with latest close price',
 'SELECT c.ticker, c.legal_name, c.sector, (ms.data->>''c'')::float AS close_price FROM companies c LEFT JOIN LATERAL (SELECT data FROM market_snapshots WHERE ticker = c.ticker AND snapshot_type = ''bar'' ORDER BY captured_at DESC LIMIT 1) ms ON true WHERE c.active = TRUE ORDER BY c.sector, c.ticker'),

('Buy Signals by Tier', 'Buy recommendations grouped by confidence tier',
 'SELECT CASE WHEN confidence >= 0.90 THEN ''Very High (90%+)'' WHEN confidence >= 0.75 THEN ''High (75-90%)'' WHEN confidence >= 0.55 THEN ''Moderate (55-75%)'' ELSE ''Low (<55%)'' END AS tier, count(*) AS count, round(avg(confidence)::numeric, 3) AS avg_confidence FROM recommendations WHERE action = ''buy'' GROUP BY 1 ORDER BY avg_confidence DESC'),

('Most Recommended Tickers', 'Top tickers by buy signal count (confidence >= 0.75)',
 'SELECT ticker, count(*) AS buy_signals, round(avg(confidence)::numeric, 3) AS avg_confidence, max(generated_at) AS latest FROM recommendations WHERE action = ''buy'' AND confidence >= 0.75 GROUP BY ticker ORDER BY buy_signals DESC LIMIT 20'),

('Strongest Bullish Trends', 'Strongest bullish trends right now',
 'SELECT entity_id AS ticker, "window", trend_direction, round(trend_strength::numeric, 4) AS strength, round(confidence::numeric, 4) AS confidence FROM trend_windows WHERE trend_direction = ''bullish'' ORDER BY trend_strength DESC LIMIT 20'),

('Bearish Signals', 'Bearish signals to watch (strength > 0.5)',
 'SELECT entity_id AS ticker, "window", trend_direction, round(trend_strength::numeric, 4) AS strength FROM trend_windows WHERE trend_direction = ''bearish'' AND trend_strength > 0.5 ORDER BY trend_strength DESC LIMIT 20'),

('High Severity Events', 'High and critical severity macro events',
 'SELECT severity, LEFT(summary, 120) AS summary, affected_sectors, created_at FROM global_events WHERE severity IN (''high'', ''critical'') ORDER BY created_at DESC LIMIT 20'),

('Skip Reason Breakdown', 'Trading decision skip reasons',
 'SELECT skip_reason, count(*) AS count FROM trading_decisions WHERE decision = ''skip'' GROUP BY skip_reason ORDER BY count DESC'),

('Act Decisions', 'Trades the engine wanted to make',
 'SELECT ticker, computed_position_size, computed_share_quantity, risk_tier_at_decision, created_at FROM trading_decisions WHERE decision = ''act'' ORDER BY created_at DESC LIMIT 20'),

('Documents Today', 'Documents processed today by type and status',
 'SELECT document_type, status, count(*) FROM documents WHERE created_at > CURRENT_DATE GROUP BY document_type, status ORDER BY document_type, count(*) DESC'),

('Ingestion Failures 6h', 'Ingestion failures in the last 6 hours',
 'SELECT s.source_type, s.source_name, ir.status, LEFT(ir.error_message, 80) AS error, ir.started_at FROM ingestion_runs ir JOIN sources s ON ir.source_id = s.id WHERE ir.status = ''failed'' AND ir.started_at > NOW() - INTERVAL ''6 hours'' ORDER BY ir.started_at DESC LIMIT 20'),

('Intelligence Coverage', 'Companies with the most documents and recommendations',
 'SELECT c.ticker, c.sector, count(DISTINCT d.id) AS documents, count(DISTINCT r.id) AS recommendations FROM companies c LEFT JOIN document_company_mentions dcm ON dcm.company_id = c.id LEFT JOIN documents d ON d.id = dcm.document_id AND d.source_type IN (''news_api'', ''filings_api'') LEFT JOIN recommendations r ON r.ticker = c.ticker WHERE c.active = TRUE GROUP BY c.ticker, c.sector ORDER BY documents DESC LIMIT 20')
ON CONFLICT (name) DO UPDATE SET sql_text = EXCLUDED.sql_text, description = EXCLUDED.description;
