"""
Agno Planning Strategy

Implementation using Agno framework for task planning.
"""

from typing import Dict, Any, AsyncIterator
import structlog

from control_plane_api.app.services.planning_strategy import PlanningStrategy
from control_plane_api.app.models.task_planning import TaskPlanResponse
from control_plane_api.app.lib.task_planning import create_planning_agent

logger = structlog.get_logger(__name__)


class AgnoPlanningStrategy(PlanningStrategy):
    """Task planning using Agno framework"""

    @property
    def name(self) -> str:
        return "agno"

    async def plan_task(self, planning_prompt: str) -> TaskPlanResponse:
        """Generate task plan using Agno (non-streaming)"""
        logger.info("using_agno_strategy_nonstream")

        # Create planning agent
        planning_agent = create_planning_agent(
            organization_id=self.organization_id,
            db=self.db,
            api_token=self.api_token
        )

        # Run agent
        response = planning_agent.run(planning_prompt)

        # Extract plan
        if isinstance(response.content, TaskPlanResponse):
            plan = response.content
        elif isinstance(response.content, dict):
            plan = TaskPlanResponse(**response.content)
        else:
            raise ValueError(f"Unexpected response type from Agno: {type(response.content)}")

        logger.info("agno_plan_generated", title=plan.title)
        return plan

    async def plan_task_stream(self, planning_prompt: str) -> AsyncIterator[Dict[str, Any]]:
        """Generate task plan using Agno (streaming)"""
        logger.info("using_agno_strategy_stream")

        # Note: Agno streaming implementation would go here
        # For now, fall back to non-streaming and yield complete event
        plan = await self.plan_task(planning_prompt)

        yield {
            "event": "complete",
            "data": {
                "plan": plan.model_dump(),
                "progress": 100,
                "message": "✅ Plan ready!"
            }
        }
