"""Shared optimizer API router with language dispatch.

This module owns the NinjaAPI router for code optimization and dispatches
to the appropriate language-specific handler based on the request's
``language`` field.  Lazy imports are used inside the function body to
avoid circular dependencies between language modules.
"""

from __future__ import annotations

from ninja import NinjaAPI

from authapp.auth import AuthenticatedRequest
from core.shared.optimizer_models import OptimizeSchema
from core.shared.optimizer_schemas import OptimizeErrorResponseSchema, OptimizeResponseSchema

optimize_api = NinjaAPI(urls_namespace="optimize")


@optimize_api.post(
    "/",
    response={
        200: OptimizeResponseSchema,
        400: OptimizeErrorResponseSchema,
        422: OptimizeErrorResponseSchema,
        500: OptimizeErrorResponseSchema,
    },
)
async def optimize(
    request: AuthenticatedRequest, data: OptimizeSchema
) -> tuple[int, OptimizeResponseSchema | OptimizeErrorResponseSchema]:
    if data.rerun_trace_id:
        from core.shared.replay import get_rerun_record, rerun_optimize  # noqa: PLC0415

        record = await get_rerun_record(data.rerun_trace_id)
        if record is not None:
            result = rerun_optimize(record, "OPTIMIZE")
            if result is not None:
                return 200, result

    if data.language in ("javascript", "typescript"):
        from core.languages.js_ts.optimizer import optimize_javascript  # noqa: PLC0415

        return await optimize_javascript(request, data)
    if data.language == "java":
        from core.languages.java.optimizer import optimize_java  # noqa: PLC0415

        return await optimize_java(request, data)
    # Default: Python optimization
    from core.languages.python.optimizer.optimizer import optimize_python  # noqa: PLC0415

    return await optimize_python(request, data)
