-- ============================================================
-- ALGORITHM_COMPOSITION — Meta-algorithm layer
-- ============================================================
-- A COMPOSITE algorithm is a named aggregation of other algorithms.
-- Example: ALG-RADHANITE-COMPOSITE combines MUNAFIQ (deception) +
-- PHARAOH (extraction) + MUTAFFIFIN (fraud) + NASL-HARTH
-- (body/progeny destruction) + HUMAN-SALE + WAR-KINDLING +
-- COVENANT-BREAKING + CREATION-ALTERATION + RIBA, and references
-- the inversion/counter algorithms RAQABA-LIBERATION + VULNERABLE-PROTECTION.
--
-- This is level 2.6 — above individual algorithms, below the Qur'an itself.
-- ============================================================

-- Flag a registry entry as a composite (not a leaf algorithm)
ALTER TABLE algorithm_registry ADD COLUMN is_composite INTEGER DEFAULT 0;

-- Composition link table
CREATE TABLE IF NOT EXISTS algorithm_composition (
    comp_id           INTEGER PRIMARY KEY AUTOINCREMENT,
    parent_algo_id    TEXT NOT NULL,
    child_algo_id     TEXT NOT NULL,
    layer_role        TEXT,                   -- DECEPTION_LAYER | EXTRACTION_LAYER | FRAUD_LAYER | WEALTH_LAYER | FINANCE_LAYER | BODY_DESECRATION_LAYER | TRAFFICKING_LAYER | ARMS_PROFITEERING_LAYER | CYCLICAL_PATTERN | METAPHYSICAL_CRIME | INVERSION | COUNTER
    execution_order   INTEGER,                -- 1..N for sequential ops; NULL for parallel
    instance_note     TEXT,
    created_date      TEXT DEFAULT (datetime('now')),
    UNIQUE (parent_algo_id, child_algo_id),
    FOREIGN KEY (parent_algo_id) REFERENCES algorithm_registry(algo_id) ON DELETE CASCADE,
    FOREIGN KEY (child_algo_id) REFERENCES algorithm_registry(algo_id) ON DELETE CASCADE,
    CHECK (parent_algo_id != child_algo_id)
);

CREATE INDEX IF NOT EXISTS idx_ac_parent ON algorithm_composition(parent_algo_id);
CREATE INDEX IF NOT EXISTS idx_ac_child ON algorithm_composition(child_algo_id);
CREATE INDEX IF NOT EXISTS idx_ac_layer ON algorithm_composition(layer_role);

-- Auto-flag parent as composite on first composition insert
CREATE TRIGGER IF NOT EXISTS trg_ac_set_composite
AFTER INSERT ON algorithm_composition
BEGIN
    UPDATE algorithm_registry SET is_composite = 1 WHERE algo_id = NEW.parent_algo_id;
END;
