import sqlite3
from app.screener.schema import ensure_screener_schema


def test_creates_all_tables(tmp_path):
    db_path = tmp_path / "test.db"
    conn = sqlite3.connect(db_path)
    ensure_screener_schema(conn)

    tables = {r[0] for r in conn.execute(
        "SELECT name FROM sqlite_master WHERE type='table'"
    ).fetchall()}

    expected = {
        "krx_master", "krx_daily_prices", "krx_flow",
        "screener_settings", "screener_runs", "screener_results",
    }
    assert expected.issubset(tables)


def test_settings_seeded_with_singleton_row(tmp_path):
    db_path = tmp_path / "test.db"
    conn = sqlite3.connect(db_path)
    ensure_screener_schema(conn)

    rows = conn.execute("SELECT id FROM screener_settings").fetchall()
    assert rows == [(1,)]


def test_idempotent(tmp_path):
    db_path = tmp_path / "test.db"
    conn = sqlite3.connect(db_path)
    ensure_screener_schema(conn)
    ensure_screener_schema(conn)        # 두 번 호출해도 에러 없어야 함

    rows = conn.execute("SELECT count(*) FROM screener_settings").fetchall()
    assert rows == [(1,)]
