-- Migration 061: Obligation Candidates + Decomposition Tracking
-- Supports Pass 0a (Obligation Extraction from Rich Controls) and
-- Pass 0b (Atomic Control Composition).
--
-- Part of the Multi-Layer Control Architecture — Decomposition Pass.

-- =============================================================================
-- 1. Obligation Candidates
--    Individual normative obligations extracted from Rich Controls (Pass 0a).
-- =============================================================================

CREATE TABLE IF NOT EXISTS obligation_candidates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    parent_control_uuid UUID NOT NULL REFERENCES canonical_controls(id),
    candidate_id VARCHAR(30) NOT NULL,
    obligation_text TEXT NOT NULL,
    action VARCHAR(500),
    object TEXT,
    condition TEXT,
    normative_strength VARCHAR(20) DEFAULT 'must'
        CHECK (normative_strength IN ('must', 'should', 'may')),
    is_test_obligation BOOLEAN DEFAULT FALSE,
    is_reporting_obligation BOOLEAN DEFAULT FALSE,
    extraction_confidence NUMERIC(3,2) DEFAULT 0.0
        CHECK (extraction_confidence >= 0 AND extraction_confidence <= 1),
    quality_flags JSONB DEFAULT '{}',
    release_state VARCHAR(30) DEFAULT 'extracted'
        CHECK (release_state IN ('extracted', 'validated', 'rejected', 'composed')),
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_oc_parent ON obligation_candidates(parent_control_uuid);
CREATE INDEX IF NOT EXISTS idx_oc_state ON obligation_candidates(release_state);
CREATE INDEX IF NOT EXISTS idx_oc_candidate ON obligation_candidates(candidate_id);

COMMENT ON TABLE obligation_candidates IS
    'Individual normative obligations extracted from Rich Controls via Pass 0a decomposition';

-- =============================================================================
-- 2. Extend canonical_controls for decomposition tracking
-- =============================================================================

ALTER TABLE canonical_controls
    ADD COLUMN IF NOT EXISTS parent_control_uuid UUID REFERENCES canonical_controls(id);

ALTER TABLE canonical_controls
    ADD COLUMN IF NOT EXISTS decomposition_method VARCHAR(30);

CREATE INDEX IF NOT EXISTS idx_cc_parent ON canonical_controls(parent_control_uuid);
