"""migrate_tarot_to_lab.py 단위 테스트 — 멱등성 + 데이터 보존."""
import sqlite3
import sys
import os
import pytest


@pytest.fixture
def src_db(tmp_path):
    p = tmp_path / "agent_office.db"
    conn = sqlite3.connect(str(p))
    conn.execute("""
        CREATE TABLE tarot_readings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            created_at TEXT, spread_type TEXT, category TEXT, question TEXT,
            cards TEXT, interpretation_json TEXT, summary TEXT, model TEXT,
            tokens_in INTEGER, tokens_out INTEGER, cost_usd REAL,
            confidence TEXT, favorite INTEGER, note TEXT
        )
    """)
    conn.execute("""
        INSERT INTO tarot_readings (id, spread_type, category, cards, model, favorite)
        VALUES (1, 'three_card', '연애', '[]', 'm', 0),
               (2, 'one_card', '재물', '[]', 'm', 1)
    """)
    conn.commit()
    conn.close()
    return str(p)


@pytest.fixture
def dst_db(tmp_path):
    return str(tmp_path / "tarot.db")


def _import_migrate(src, dst, monkeypatch):
    monkeypatch.setenv("AGENT_OFFICE_DB", src)
    monkeypatch.setenv("TAROT_DB", dst)
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))
    import migrate_tarot_to_lab as m
    import importlib
    importlib.reload(m)
    return m


def test_first_run_copies_all_rows(src_db, dst_db, monkeypatch):
    m = _import_migrate(src_db, dst_db, monkeypatch)
    moved = m.migrate()
    assert moved == 2
    conn = sqlite3.connect(dst_db)
    rows = conn.execute("SELECT id, spread_type, category FROM tarot_readings ORDER BY id").fetchall()
    conn.close()
    assert rows == [(1, "three_card", "연애"), (2, "one_card", "재물")]


def test_idempotent_second_run(src_db, dst_db, monkeypatch):
    m = _import_migrate(src_db, dst_db, monkeypatch)
    m.migrate()
    moved2 = m.migrate()
    assert moved2 == 0


def test_partial_migration(src_db, dst_db, monkeypatch):
    """dst에 id=1만 있는 상태에서 다시 돌리면 id=2만 옮김."""
    m = _import_migrate(src_db, dst_db, monkeypatch)
    m.migrate()
    conn = sqlite3.connect(dst_db)
    conn.execute("DELETE FROM tarot_readings WHERE id=2")
    conn.commit()
    conn.close()
    moved = m.migrate()
    assert moved == 1
