"""
# Protected Directory

⚠️ Files in this directory are auto-generated by ND-SDK.

**DO NOT EDIT** - Your changes will be lost on regeneration.

{{ endpoint.description }}
"""

{% if web_framework == 'flask' %}
from flask import Blueprint, request, jsonify
from ..dependencies import get_service

from pydantic import ValidationError
from ..models.{{ endpoint.name }} import (
    {{ endpoint.name | camel_case }}Request,
    {{ endpoint.name | camel_case }}Response,
)
{% if endpoint.cache.enabled %}
from nd_sdk.caching import cache
{% endif %}
from nd_sdk import initialize_sdk, get_initialized_component

initialize_sdk.init()

logger = get_initialized_component('logger')
tracer = get_initialized_component('tracer')
metrics = get_initialized_component('metrics')

blueprint = Blueprint("{{ endpoint.name }}", __name__, url_prefix="{{ web.url_prefix }}")

@blueprint.route("{{ endpoint.path }}", methods=["{{ endpoint.method.upper() }}"])
@logger.set_logger()
@tracer.set_tracer(kind='SERVER')
@metrics.set_metrics()
{% if endpoint.cache.enabled %}
@cache(ttl={{ endpoint.cache.ttl }})
{% endif %}
def {{ endpoint.name }}(
{% for param in endpoint.params %}
{% if param.in == "path" %}
    {{ param.name }},
{% endif %}
{% endfor %}
):
    """
    {{ endpoint.description }}
    """
    logger = get_initialized_component('logger')
    try:
        logger.info("Processing {{ endpoint.name }} request")
        logger.debug(f"Request received with params: { request.args } and body: { request.get_data(as_text=True) }")

        # ---- Input validation ----
        payload = {{ endpoint.name | camel_case }}Request({% if endpoint.params %}{% if endpoint.input_type == "form" %}**request.form.to_dict(){% else %}**request.get_json(silent=True){% endif %}{% endif %})

        # ---- Business logic ----
        service = get_service("{{ endpoint.name }}")
        {% if endpoint.params %}
        result = service.execute(**payload.model_dump())
        {% else %}
        result = service.execute()
        {% endif %}

{% if endpoint.params %}
        # ---- Output validation ----
        response = {{ endpoint.name | camel_case }}Response(**result)
        return jsonify(response.model_dump()), 200
{% else %}
        return jsonify(result), 200
{% endif %}

{% if endpoint.params %}
    except ValidationError as ve:
        logger.warning(f"Validation error in {{ endpoint.name }}: {ve}")
        return jsonify({"errors": ve.errors()}), 422
{% endif %}

    except Exception as e:
        logger.error(f"Error in {{ endpoint.name }}: {str(e)}")
        return jsonify({"error": str(e)}), 500

{% else %}

from fastapi import APIRouter, HTTPException
from nd_sdk.observability import get_logger
from app.dependencies import get_service

{% if endpoint.params %}
from pydantic import ValidationError
from app.models.{{ endpoint.name }} import (
    {{ endpoint.name | camel_case }}Request,
    {{ endpoint.name | camel_case }}Response,
)
{% endif %}
{% if endpoint.cache.enabled %}
from nd_sdk.caching import cache
{% endif %}

logger = get_logger(__name__)
router = APIRouter()

@router.{{ endpoint.method.lower() }}(
    "{{ endpoint.path }}"{% if endpoint.params %},
    response_model={{ endpoint.name | camel_case }}Response{% endif %}
)
{% if endpoint.cache.enabled %}
@cache(ttl={{ endpoint.cache.ttl }})
{% endif %}
async def {{ endpoint.name }}(
{% for param in endpoint.params %}
{% if param.in == "path" %}
    {{ param.name }}: {{ param.type }},
{% endif %}
{% endfor %}
{% if endpoint.params and endpoint.method in ["POST", "PUT", "PATCH"] %}
    request: {{ endpoint.name | camel_case }}Request,
{% endif %}
):
    """
    {{ endpoint.description }}
    """

    try:
        logger.info("Processing {{ endpoint.name }} request")
        service = get_service("{{ endpoint.name }}")
        result = service.execute()

{% if endpoint.params %}
        return {{ endpoint.name | camel_case }}Response(**result)
{% else %}
        return result
{% endif %}

{% if endpoint.params %}
    except ValidationError as ve:
        logger.warning(f"Validation error in {{ endpoint.name }}: {ve}")
        raise HTTPException(status_code=422, detail=ve.errors())
{% endif %}

    except Exception as e:
        logger.error(f"Error in {{ endpoint.name }}: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

{% endif %}
