import json
import asyncio
from backend.engine.engine import model_engine
from backend.app.plan.schemas import PlanTriggerRequest
from utils.logger import setup_logger

logger = setup_logger()


def handler(event, context):
    """
    Lambda handler that triggers the model engine for each SQS message.
    """
    for record in event.get("Records", []):
        try:
            body_dict = json.loads(record["body"])
            payload = PlanTriggerRequest.model_validate(body_dict)
            asyncio.run(model_engine(payload))
        except Exception as e:
            logger.error(f"Failed to process record: {e}")
