import os, tempfile

def _fresh_db(monkeypatch):
    tmp = tempfile.mkdtemp()
    from app import db
    monkeypatch.setattr(db, "DB_PATH", os.path.join(tmp, "stock.db"))
    db.init_db()
    return db

def test_holdings_signals_table_and_upsert(monkeypatch):
    db = _fresh_db(monkeypatch)
    db.upsert_holdings_signal(date="2026-05-29", ticker="005930", name="삼성전자",
        action="hold", tech_score=72.0, exit_flags={"stop_loss": False},
        issues=[{"type": "news", "severity": "low", "summary": "x"}],
        close=80000, pnl_rate=5.2, reasons="강건")
    db.upsert_holdings_signal(date="2026-05-29", ticker="005930", name="삼성전자",
        action="trim", tech_score=60.0, exit_flags={"ma50_break": True},
        issues=[], close=79000, pnl_rate=3.0, reasons="MA50 이탈")
    rows = db.get_holdings_signals(date="2026-05-29")
    assert len(rows) == 1                       # upsert 멱등
    assert rows[0]["action"] == "trim"
    assert rows[0]["exit_flags"]["ma50_break"] is True   # JSON 역직렬화
    hist = db.get_holdings_signal_history("005930", limit=30)
    assert len(hist) == 1


def test_get_latest_holdings_date(monkeypatch):
    db = _fresh_db(monkeypatch)
    # empty table → None
    assert db.get_latest_holdings_date() is None
    # after an upsert → returns that date
    db.upsert_holdings_signal(
        date="2026-05-30", ticker="005930", name="삼성전자",
        action="hold", tech_score=70.0, exit_flags={}, issues=[],
        close=80000, pnl_rate=4.0, reasons="테스트",
    )
    assert db.get_latest_holdings_date() == "2026-05-30"
