-- p2_decision_fusion_columns.sql
-- 2026-04-26 P2-DB-Fix by Claude — db-expert P0 三修（P0.3）
-- P2.1 DecisionFusionEngine 必要欄位 + partial index
-- ADR-085 鐵律：AI 學習成果不可存 Cache，fusion 分數必須落地 PG
--
-- 執行方式：DBA 手動執行（禁止 alembic upgrade / CI 自動跑）
-- CONCURRENTLY 必須在 transaction 外單獨執行

BEGIN;

ALTER TABLE approval_records
    ADD COLUMN IF NOT EXISTS composite_score        REAL,
    ADD COLUMN IF NOT EXISTS complexity_tier        VARCHAR(16),
    ADD COLUMN IF NOT EXISTS decision_fusion_details JSONB;

ALTER TABLE approval_records
    ADD CONSTRAINT IF NOT EXISTS chk_complexity_tier CHECK (
        complexity_tier IS NULL
        OR complexity_tier IN ('low', 'medium', 'high', 'critical')
    );

COMMENT ON COLUMN approval_records.composite_score
    IS 'P2.1 DecisionFusion 合成分數（0.0-1.0），方法 III 加權結果';
COMMENT ON COLUMN approval_records.complexity_tier
    IS 'P2.1 告警複雜度分層：low / medium / high / critical';
COMMENT ON COLUMN approval_records.decision_fusion_details
    IS 'P2.1 DecisionFusionEngine: openclaw_score / hermes_score / playbook_score / mcp_health_score / elephant_score';

COMMIT;

-- CONCURRENTLY 必須在 transaction 外執行（不可放在 BEGIN/COMMIT 內）
CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_approval_composite_score
    ON approval_records (composite_score)
    WHERE composite_score IS NOT NULL;

CREATE INDEX CONCURRENTLY IF NOT EXISTS ix_approval_complexity_tier
    ON approval_records (complexity_tier)
    WHERE complexity_tier IS NOT NULL;
