from __future__ import annotations

import logging
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException

from codeflash_api.auth._deps import require_auth
from codeflash_api.auth.models import AuthenticatedUser  # noqa: TC001
from codeflash_api.logging.schemas import (
    LogFeaturesErrorResponse,
    LogFeaturesRequest,
)
from codeflash_api.optimize._context import validate_trace_id

log = logging.getLogger(__name__)

router = APIRouter()


@router.post(
    "/ai/log_features",
    responses={
        200: {"description": "Features logged successfully"},
        400: {"model": LogFeaturesErrorResponse},
        500: {"model": LogFeaturesErrorResponse},
    },
    status_code=200,
)
async def log_features(
    data: LogFeaturesRequest,
    user: Annotated[AuthenticatedUser, Depends(require_auth)],
) -> None:
    """
    Log optimization features for a trace.
    """
    if not user.should_log_features:
        return

    if not validate_trace_id(data.trace_id):
        raise HTTPException(
            status_code=400,
            detail="Invalid trace ID. Please provide a valid UUIDv4.",
        )

    try:
        # DB upsert deferred — will call asyncpg here once
        # the database layer for optimization_features is wired.
        log.debug(
            "log_features accepted: trace_id=%s user=%s",
            data.trace_id,
            user.user_id,
        )
    except Exception:
        log.exception(
            "Failed to log features: trace_id=%s",
            data.trace_id,
        )
        raise HTTPException(
            status_code=500,
            detail="Internal error while logging features.",
        ) from None
