from .base import BaseAgent
from ..db import create_task, update_task_status, add_log
from ..curator.pipeline import curate_weekly, CuratorError


class LottoAgent(BaseAgent):
    agent_id = "lotto"
    display_name = "로또 큐레이터"

    async def on_schedule(self) -> None:
        if self.state != "idle":
            return
        await self._run(source="auto")

    async def on_command(self, action: str, params: dict) -> dict:
        if action in ("curate_now", "curate_weekly"):
            return await self._run(source="manual")
        if action == "status":
            return {"ok": True, "message": f"{self.state}: {self.state_detail}"}
        return {"ok": False, "message": f"unknown action: {action}"}

    async def on_approval(self, task_id: str, approved: bool, feedback: str = "") -> None:
        pass

    async def _run(self, source: str) -> dict:
        task_id = create_task(self.agent_id, "curate_weekly", {"source": source})
        await self.transition("working", "후보 수집 및 AI 큐레이션 중...", task_id)
        try:
            result = await curate_weekly(source=source)
            update_task_status(task_id, "succeeded", result_data={
                k: v for k, v in result.items() if k != "payload"
            })
            await self.transition("reporting", f"#{result['draw_no']} 브리핑 저장 완료")
            add_log(self.agent_id, f"큐레이션 완료: #{result['draw_no']} conf={result['confidence']}", task_id=task_id)

            # 텔레그램 헤드라인 푸시 (실패해도 큐레이션은 성공으로 마감)
            try:
                from ..notifiers.telegram_lotto import send_curator_briefing
                await send_curator_briefing(result["payload"])
            except Exception as e:
                add_log(self.agent_id, f"텔레그램 알림 실패: {e}", level="warning", task_id=task_id)

            await self.transition("idle", "대기 중")
            return {"ok": True, **{k: v for k, v in result.items() if k != "payload"}}
        except CuratorError as e:
            update_task_status(task_id, "failed", result_data={"error": str(e)})
            add_log(self.agent_id, f"큐레이션 실패: {e}", level="error", task_id=task_id)
            await self.transition("idle", "오류")
            return {"ok": False, "message": str(e)}
        except Exception as e:
            update_task_status(task_id, "failed", result_data={"error": str(e)})
            add_log(self.agent_id, f"큐레이션 예외: {e}", level="error", task_id=task_id)
            await self.transition("idle", "오류")
            return {"ok": False, "message": f"{type(e).__name__}: {e}"}
