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 unittest.mock import AsyncMock

import pytest

from app.agents.insta import InstaAgent


@pytest.fixture(autouse=True)
def _init_db():
    import gc
    gc.collect()
    if os.path.exists(_TMP):
        os.remove(_TMP)
    from app.db import init_db
    init_db()
    yield
    gc.collect()


@pytest.mark.asyncio
async def test_on_command_collect_trends_dispatches(monkeypatch):
    agent = InstaAgent()
    fake_collect = AsyncMock(return_value={"task_id": "tcollect"})
    fake_status = AsyncMock(return_value={"status": "succeeded", "result_id": 8,
                                          "message": "naver:5, google:3"})

    monkeypatch.setattr("app.agents.insta.service_proxy.insta_collect_trends", fake_collect)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_task_status", fake_status)
    monkeypatch.setattr("app.agents.insta.messaging.send_raw", AsyncMock(return_value={"ok": True}))

    result = await agent.on_command("collect_trends", {})
    assert result["ok"] is True
    fake_collect.assert_awaited()


@pytest.mark.asyncio
async def test_on_schedule_loads_preferences(monkeypatch):
    """on_schedule이 preferences를 가져오는지 확인."""
    agent = InstaAgent()

    fake_collect = AsyncMock(return_value={"task_id": "t1"})
    fake_extract = AsyncMock(return_value={"task_id": "t2"})
    fake_status = AsyncMock(side_effect=[
        {"status": "succeeded", "result_id": 0},
        {"status": "succeeded", "result_id": 0},
    ])
    fake_keywords = AsyncMock(return_value=[
        {"id": 1, "keyword": "K", "category": "economy", "score": 0.9},
    ])
    fake_prefs = AsyncMock(return_value={"economy": 0.6, "psychology": 0.4})

    monkeypatch.setattr("app.agents.insta.service_proxy.insta_collect", fake_collect)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_extract", fake_extract)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_task_status", fake_status)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_list_keywords", fake_keywords)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_preferences", fake_prefs)
    monkeypatch.setattr("app.agents.insta.messaging.send_raw", AsyncMock(return_value={"ok": True}))

    agent.state = "idle"
    await agent.on_schedule()

    fake_prefs.assert_awaited()
