-- Migration 152: Atom-level topic classification (Haiku one-time pass)
-- Pro atomarem Control x Use-Case: relevant? + Sub-Thema + kanonische Pflicht.
-- Atom-grain Nachfolger des master-grain mc_use_case_mappings — die Master-
-- Komposition (gpre2 object-only Clustering) ist als Topic-Einheit unbrauchbar
-- (Mega-Cluster). Die Atome sind kohaerent; diese Tabelle traegt das Ergebnis
-- des einmaligen Haiku-Passes (Praezision + Organisation + Dedup). Strikt add-only.
-- Laufzeit liest NUR diese Tabelle (kein LLM live). [migration-approved]

SET search_path TO compliance, public;

DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.tables
             WHERE table_schema = 'compliance'
               AND table_name = 'canonical_controls') THEN

    CREATE TABLE IF NOT EXISTS atom_classification (
        control_uuid UUID NOT NULL
            REFERENCES canonical_controls(id) ON DELETE CASCADE,
        -- Registry-Key; KEIN SQL-CHECK -> neuer Use Case ohne Migration.
        use_case VARCHAR(40) NOT NULL,
        relevant BOOLEAN NOT NULL DEFAULT TRUE,
        sub_topic VARCHAR(60),
        canonical_obligation TEXT,
        method VARCHAR(20) NOT NULL DEFAULT 'llm'
            CHECK (method IN ('auto', 'manual', 'llm', 'seed')),
        model VARCHAR(60),
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        PRIMARY KEY (control_uuid, use_case)
    );
    CREATE INDEX IF NOT EXISTS idx_atomcls_use_case
        ON atom_classification(use_case);
    CREATE INDEX IF NOT EXISTS idx_atomcls_uc_rel
        ON atom_classification(use_case, relevant);
    CREATE INDEX IF NOT EXISTS idx_atomcls_subtopic
        ON atom_classification(use_case, sub_topic);

  END IF;
END $$;
