"""Shared testgen API router with language dispatch.

This module owns the NinjaAPI router for test generation 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.testgen_models import TestGenErrorResponseSchema, TestGenResponseSchema, TestGenSchema

testgen_api = NinjaAPI(urls_namespace="testgen")


@testgen_api.post(
    "/",
    response={
        200: TestGenResponseSchema,
        400: TestGenErrorResponseSchema,
        422: TestGenErrorResponseSchema,
        500: TestGenErrorResponseSchema,
    },
)
async def testgen(
    request: AuthenticatedRequest, data: TestGenSchema
) -> tuple[int, TestGenResponseSchema | TestGenErrorResponseSchema]:
    if data.rerun_trace_id:
        from core.shared.replay import get_rerun_record, rerun_testgen  # noqa: PLC0415

        record = await get_rerun_record(data.rerun_trace_id)
        if record is not None:
            result = rerun_testgen(record, data.test_index or 0)
            if result is not None:
                return 200, result

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

        return await testgen_javascript(request, data)
    if data.language == "java":
        from core.languages.java.testgen import testgen_java  # noqa: PLC0415

        return await testgen_java(request, data)
    # Default: Python test generation
    from core.languages.python.testgen.generate import testgen_python  # noqa: PLC0415

    return await testgen_python(request, data)
