import os
import sys
import tempfile

_fd, _TMP = tempfile.mkstemp(suffix=".db")
os.close(_fd)
os.unlink(_TMP)
os.environ["AGENT_OFFICE_DB_PATH"] = _TMP

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.agents.insta import _dedup_and_filter_keywords, KEYWORD_MIN_SCORE


def test_filters_below_threshold():
    """score < 임계값(0.7) 키워드는 제외."""
    kws = [
        {"id": 1, "keyword": "금리인하", "category": "경제", "score": 0.9},
        {"id": 2, "keyword": "환율", "category": "경제", "score": 0.6},  # 컷
        {"id": 3, "keyword": "반도체", "category": "경제", "score": 0.71},
    ]
    out = _dedup_and_filter_keywords(kws, min_score=0.7)
    kept = {k["keyword"] for k in out}
    assert kept == {"금리인하", "반도체"}


def test_dedup_keeps_highest_score():
    """동일 keyword 중복 시 최고 score 1개만 유지."""
    kws = [
        {"id": 1, "keyword": "AI", "category": "경제", "score": 0.75},
        {"id": 2, "keyword": "AI", "category": "기술", "score": 0.92},  # 같은 키워드, 더 높음
    ]
    out = _dedup_and_filter_keywords(kws, min_score=0.7)
    assert len(out) == 1
    assert out[0]["id"] == 2
    assert out[0]["score"] == 0.92


def test_sorted_by_score_desc():
    kws = [
        {"id": 1, "keyword": "a", "category": "c", "score": 0.72},
        {"id": 2, "keyword": "b", "category": "c", "score": 0.95},
        {"id": 3, "keyword": "c", "category": "c", "score": 0.80},
    ]
    out = _dedup_and_filter_keywords(kws, min_score=0.7)
    assert [k["keyword"] for k in out] == ["b", "c", "a"]


def test_empty_when_all_below_threshold():
    kws = [{"id": 1, "keyword": "x", "category": "c", "score": 0.4}]
    assert _dedup_and_filter_keywords(kws, min_score=0.7) == []


def test_default_threshold_is_0_7():
    assert KEYWORD_MIN_SCORE == 0.7
