import sqlite3
import pytest

from app import db as db_module


@pytest.fixture(autouse=True)
def fresh_db(monkeypatch, tmp_path):
    db_file = tmp_path / "test_saju.db"
    monkeypatch.setattr(db_module, "DB_PATH", str(db_file))
    yield
    try:
        if db_file.exists():
            db_file.unlink()
    except PermissionError:
        pass


def test_new_columns_exist():
    db_module.init_db()
    conn = sqlite3.connect(db_module.DB_PATH)
    cols = [row[1] for row in conn.execute("PRAGMA table_info(saju_records)").fetchall()]
    conn.close()
    assert "fortune_scores_json" in cols
    assert "lucky_json" in cols
    assert "monthly_flow_json" in cols


def test_idempotent_init():
    db_module.init_db()
    db_module.init_db()  # 두 번째 호출 — ALTER TABLE이 OperationalError 캐치


def test_save_and_get_with_new_fields():
    db_module.init_db()
    rid = db_module.save_saju_record({
        "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": 14,
        "gender": "male", "calendar_type": "solar",
        "saju_data": {"day_stem": "辛"},
        "analysis_data": {"element_balance": {"金": 3.0}},
        "daeun_data": [{"age": 10}],
        "interpretation_json": {"items": []},
        "model": "claude-sonnet-4-6",
        "tokens_in": 100, "tokens_out": 200, "cost_usd": 0.005,
        "fortune_scores_json": {"wealth": 80, "romance": 60, "social": 70, "career": 75, "overall": 73},
        "lucky_json": {"color": ["청록"], "number": 5, "direction": "동쪽", "good_signs": ["S1"], "warnings": []},
        "monthly_flow_json": [{"month": 1, "stem": "壬", "branch": "寅", "score": 65, "label": "변동"}],
    })
    row = db_module.get_saju_record(rid)
    assert row["fortune_scores"]["wealth"] == 80
    assert row["lucky"]["number"] == 5
    assert row["monthly_flow"][0]["month"] == 1


def test_save_without_new_fields_backwards_compat():
    db_module.init_db()
    rid = db_module.save_saju_record({
        "birth_year": 1990, "birth_month": 5, "birth_day": 15, "birth_hour": None,
        "gender": "male",
        "saju_data": {}, "analysis_data": {}, "daeun_data": [],
        "model": "x",
    })
    row = db_module.get_saju_record(rid)
    assert row["fortune_scores"] is None
    assert row["lucky"] is None
    assert row["monthly_flow"] is None
