/**
 * Migration: 019 - Backfill kg_triple from memory_item (Issue #90)
 * Description: 기존 semantic memory_item 중 subject,predicate,object 있는 행을 kg_triple에 채움
 * Version: 19.0
 * Date: 2026-02-08
 */
/**
 * Backfill kg_triple from existing memory_item (Issue #90)
 *
 * type='semantic'이고 subject, predicate, object가 모두 NOT NULL인 행을 스캔하여
 * (subject, predicate, object)당 한 행만 kg_triple에 INSERT. 동일 (s,p,o) 여러 개면
 * created_at 기준 가장 이른 하나를 representative로 사용.
 */
export class BackfillKgTripleFromMemoryItemMigration {
    version = '19.0';
    name = 'backfill-kg-triple-from-memory-item';
    description = 'Backfill kg_triple from existing semantic memory_item (Issue #90)';
    tableExists(db, tableName) {
        const result = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`).get(tableName);
        return !!result;
    }
    async validateBefore(db) {
        if (!this.tableExists(db, 'memory_item')) {
            throw new Error('memory_item table does not exist.');
        }
        if (!this.tableExists(db, 'kg_triple')) {
            throw new Error('kg_triple table does not exist. Run migration 018 first.');
        }
        if (this.tableExists(db, 'memento_schema_version')) {
            const row = db.prepare(`SELECT version FROM memento_schema_version WHERE version = ?`).get('19.0');
            if (row) {
                throw new Error('Migration 019 has already been applied.');
            }
        }
    }
    async up(db) {
        const rows = db.prepare(`
      SELECT id, subject, predicate, object, owner_id, process_id, session_id, created_at
      FROM memory_item
      WHERE type = 'semantic'
        AND subject IS NOT NULL AND subject != ''
        AND predicate IS NOT NULL AND predicate != ''
        AND object IS NOT NULL AND object != ''
      ORDER BY created_at ASC
    `).all();
        const seen = new Set();
        const insert = db.prepare(`
      INSERT OR IGNORE INTO kg_triple (id, subject, predicate, object, owner_id, process_id, session_id, representative_memory_id, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
        for (const row of rows) {
            const key = `${row.subject}\t${row.predicate}\t${row.object}`;
            if (seen.has(key))
                continue;
            seen.add(key);
            const kgId = `triple_backfill_${row.id}`;
            insert.run(kgId, row.subject, row.predicate, row.object, row.owner_id ?? null, row.process_id ?? null, row.session_id ?? null, row.id, row.created_at ?? null);
        }
        // 스키마 버전 기록은 MigrationRunner.recordVersion()이 수행함. 여기서 INSERT 시 중복으로 UNIQUE 오류 발생.
    }
    async down(db) {
        // Backfill은 비가역. down은 no-op (제거 시 신규 추출 triple과 구분 불가).
        if (this.tableExists(db, 'memento_schema_version')) {
            db.prepare('DELETE FROM memento_schema_version WHERE version = ?').run('19.0');
        }
    }
    async validateAfter(db) {
        // backfill 후 kg_triple 존재 여부만 검증. 버전 기록은 MigrationRunner가 이후 recordVersion()으로 수행.
        if (!this.tableExists(db, 'kg_triple')) {
            throw new Error('kg_triple table missing after 019 backfill');
        }
    }
}
//# sourceMappingURL=019-backfill-kg-triple-from-memory-item.js.map