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 patch, AsyncMock, MagicMock

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_extract_dispatches(monkeypatch):
    agent = InstaAgent()
    fake_collect = AsyncMock(return_value={"task_id": "tcollect"})
    fake_extract = AsyncMock(return_value={"task_id": "textract"})
    fake_status = AsyncMock(side_effect=[
        {"status": "succeeded", "result_id": 0},
        {"status": "succeeded", "result_id": 0},
    ])
    fake_keywords = AsyncMock(return_value=[
        {"id": 1, "keyword": "K1", "category": "economy", "score": 0.9},
        {"id": 2, "keyword": "K2", "category": "psychology", "score": 0.8},
    ])

    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.messaging.send_raw", AsyncMock(return_value={"ok": True}))

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


@pytest.mark.asyncio
async def test_on_callback_render_kicks_pipeline(monkeypatch):
    agent = InstaAgent()
    fake_kw = AsyncMock(return_value={"id": 7, "keyword": "테스트", "category": "economy"})
    fake_create = AsyncMock(return_value={"task_id": "tslate"})
    fake_status = AsyncMock(side_effect=[
        {"status": "processing"},
        {"status": "succeeded", "result_id": 42},
    ])
    fake_slate = AsyncMock(return_value={
        "id": 42, "status": "rendered",
        "suggested_caption": "캡션", "hashtags": ["#a", "#b"],
        "assets": [{"page_index": i, "file_path": f"/x/{i}.png"} for i in range(1, 11)],
    })
    fake_bytes = AsyncMock(side_effect=[b"PNG"] * 10)
    fake_send_media = AsyncMock(return_value={"ok": True})

    monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_keyword", fake_kw)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_create_slate", fake_create)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_task_status", fake_status)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_slate", fake_slate)
    monkeypatch.setattr("app.agents.insta.service_proxy.insta_get_asset_bytes", fake_bytes)
    monkeypatch.setattr("app.agents.insta._send_media_group", fake_send_media)
    monkeypatch.setattr("app.agents.insta.messaging.send_raw", AsyncMock(return_value={"ok": True}))

    out = await agent.on_callback("render", {"keyword_id": 7})
    assert out["ok"] is True
    fake_create.assert_awaited()
    fake_send_media.assert_awaited()
