CREATE UNIQUE INDEX IF NOT EXISTS idx_kd_external_id ON knowledge_documents(external_id);
CREATE INDEX IF NOT EXISTS idx_kd_language_region_status ON knowledge_documents(language, region_code, status);
CREATE INDEX IF NOT EXISTS idx_kd_source_hash ON knowledge_documents(source_hash);
CREATE INDEX IF NOT EXISTS idx_kd_validity ON knowledge_documents(valid_from, valid_to);
CREATE INDEX IF NOT EXISTS idx_kc_document_id ON knowledge_chunks(document_id);
CREATE INDEX IF NOT EXISTS idx_kc_language_region ON knowledge_chunks(language, region_code);
CREATE INDEX IF NOT EXISTS idx_kc_content_hash ON knowledge_chunks(content_hash);
CREATE INDEX IF NOT EXISTS idx_kc_tsv ON knowledge_chunks USING GIN(tsv);
DO $$
BEGIN
    BEGIN
        CREATE INDEX IF NOT EXISTS idx_kc_embedding_hnsw ON knowledge_chunks USING hnsw (embedding vector_cosine_ops);
    EXCEPTION WHEN OTHERS THEN
        BEGIN
            CREATE INDEX IF NOT EXISTS idx_kc_embedding_ivfflat ON knowledge_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
        EXCEPTION WHEN OTHERS THEN
            RAISE NOTICE 'vector index creation skipped: %', SQLERRM;
        END;
    END;
END $$;
