import os, sqlite3, tempfile, datetime as dt
import pytest

@pytest.fixture
def db(monkeypatch, tmp_path):
    from app import db as _db
    monkeypatch.setattr(_db, "DB_PATH", str(tmp_path / "stock.db"))
    _db.init_db()
    return _db

def test_watchlist_add_get_remove(db):
    db.add_watchlist("005930", "삼성전자", note="관심")
    db.add_watchlist("005930", "삼성전자")  # 멱등
    wl = db.get_watchlist()
    assert [w["ticker"] for w in wl] == ["005930"]
    assert wl[0]["name"] == "삼성전자"
    assert db.remove_watchlist("005930") is True
    assert db.get_watchlist() == []

def test_alert_state_edge_firing_and_clear(db):
    key = ("005930", "buy", "buy_breakout")
    assert db.get_alert_state_firing() == set()
    db.set_alert_firing(*key, firing=True, at_iso="2026-07-02T00:01:00Z")
    assert key in db.get_alert_state_firing()
    db.set_alert_firing(*key, firing=False)
    assert key not in db.get_alert_state_firing()

def test_alert_history_records_and_reads(db):
    db.add_alert_history("005930", "삼성전자", "buy", "buy_breakout", 71500, {"vol": 2.1})
    rows = db.get_alert_history(days=7)
    assert len(rows) == 1
    assert rows[0]["ticker"] == "005930" and rows[0]["kind"] == "buy"
    assert rows[0]["detail"]["vol"] == 2.1

def test_alert_history_days_filter_format_consistency(db):
    """fired_at은 ISO(T/Z)로 저장 — 필터도 ISO여야 경계일 비교가 정확.
    7일 경계 밖(정확히 7일 전 자정) 레코드는 제외되어야 한다. 포맷 불일치면 잘못 포함됨."""
    db.add_alert_history("005930", "삼성", "buy", "buy_breakout", 71500, {})  # now
    conn = sqlite3.connect(db.DB_PATH)
    conn.execute(
        "INSERT INTO trade_alert_history(ticker,name,kind,condition,price,detail_json,fired_at) "
        "VALUES('000660','SK','sell','sell_stop_loss',60000,'{}', "
        "strftime('%Y-%m-%dT%H:%M:%fZ','now','-7 days','start of day'))"
    )
    conn.commit(); conn.close()
    tickers = [r["ticker"] for r in db.get_alert_history(days=7)]
    assert "005930" in tickers
    assert "000660" not in tickers
