from typing import Annotated, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from apps.api.dependencies import get_current_user, get_current_tenant
from infrastructure.database.session import get_db
from modules.identity.models import User
from modules.tenants.models import Tenant, TenantMember
from modules.i18n.schemas import (
    LocaleResponse,
    SetLocaleRequest,
    SaveTranslationRequest,
    TranslationBundleResponse,
    TranslationItemResponse,
    MissingTranslationsResponse,
    AuditSummaryResponse,
    AITranslationRequest,
    AITranslationResponse,
    TenantLanguageSettings,
    UpdateTenantLanguageSettings,
    BotLocaleRequest,
)
from modules.i18n.service import I18nService
from shared.schemas import ApiResponse

router = APIRouter(prefix="/i18n", tags=["Internationalization (i18n)"])


@router.get("/locales", response_model=ApiResponse[list[LocaleResponse]], status_code=status.HTTP_200_OK)
async def list_locales(
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    locales = service.get_supported_locales()
    return ApiResponse(
        message="Supported languages catalog retrieved",
        data=[LocaleResponse.model_validate(loc) for loc in locales],
    )


@router.get("/audit", response_model=ApiResponse[AuditSummaryResponse], status_code=status.HTTP_200_OK)
async def audit_translations_coverage(
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    summary = await service.audit_all_locales()
    return ApiResponse(
        message="Translation audit summary generated",
        data=summary,
    )


@router.get("/missing", response_model=ApiResponse[MissingTranslationsResponse], status_code=status.HTTP_200_OK)
async def detect_missing_translations(
    locale: str = Query(description="Target locale code, e.g. hi, es, ar"),
    namespace: str = Query(default="bot", description="Namespace: bot, dashboard, payments, errors"),
    db: Annotated[AsyncSession, Depends(get_db)] = None,
):
    service = I18nService(db)
    report = await service.get_missing_translations(locale=locale, namespace=namespace)
    return ApiResponse(
        message=f"Missing translations checked for '{locale}' in namespace '{namespace}'",
        data=report,
    )


@router.get("/translations/pending", response_model=ApiResponse[list[TranslationItemResponse]], status_code=status.HTTP_200_OK)
async def list_pending_translations(
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    pending = await service.list_pending_translations()
    return ApiResponse(
        message="Pending translation drafts awaiting approval",
        data=[TranslationItemResponse.model_validate(p) for p in pending],
    )


@router.get("/translations/{locale}", response_model=ApiResponse[TranslationBundleResponse], status_code=status.HTTP_200_OK)
async def get_translation_bundle(
    locale: str,
    namespace: str = Query(default="dashboard", description="Namespace, e.g. dashboard, bot, payments, errors"),
    db: Annotated[AsyncSession, Depends(get_db)] = None,
):
    service = I18nService(db)
    bundle = await service.get_bundle(locale=locale, namespace=namespace)
    return ApiResponse(
        message="Translation bundle retrieved",
        data=TranslationBundleResponse(
            locale=locale,
            namespace=namespace,
            translations=bundle,
        ),
    )


@router.post("/user/locale", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def set_user_language(
    req: SetLocaleRequest,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    await service.set_user_locale(current_user.id, req.locale)
    return ApiResponse(
        message=f"Language updated to '{req.locale}'",
        data=None,
    )


@router.post("/translations", response_model=ApiResponse[None], status_code=status.HTTP_201_CREATED)
async def save_custom_translation(
    req: SaveTranslationRequest,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    tenant_uuid = UUID(req.tenant_id) if req.tenant_id else None
    await service.save_custom_translation(
        locale=req.locale,
        namespace=req.namespace,
        key=req.key,
        value=req.value,
        tenant_id=tenant_uuid,
        is_approved=req.is_approved,
    )
    return ApiResponse(
        message="Custom translation saved successfully",
        data=None,
    )


@router.post("/ai/translate", response_model=ApiResponse[AITranslationResponse], status_code=status.HTTP_200_OK)
async def ai_suggest_translation(
    req: AITranslationRequest,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    result = await service.ai_suggest_translation(req)
    return ApiResponse(
        message="AI-assisted translation generated",
        data=result,
    )


@router.post("/translations/{translation_id}/approve", response_model=ApiResponse[TranslationItemResponse], status_code=status.HTTP_200_OK)
async def approve_translation(
    translation_id: UUID,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    approved = await service.approve_translation(translation_id)
    return ApiResponse(
        message="Translation approved and published live",
        data=TranslationItemResponse.model_validate(approved),
    )


@router.post("/translations/{translation_id}/reject", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def reject_translation(
    translation_id: UUID,
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    await service.reject_translation(translation_id)
    return ApiResponse(
        message="Draft translation rejected and deleted",
        data=None,
    )


@router.get("/tenant/settings", response_model=ApiResponse[TenantLanguageSettings], status_code=status.HTTP_200_OK)
async def get_tenant_language_settings(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = I18nService(db)
    settings = await service.get_tenant_languages(tenant.id)
    return ApiResponse(
        message="Tenant language settings retrieved",
        data=settings,
    )


@router.put("/tenant/settings", response_model=ApiResponse[TenantLanguageSettings], status_code=status.HTTP_200_OK)
async def update_tenant_language_settings(
    req: UpdateTenantLanguageSettings,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = I18nService(db)
    updated = await service.update_tenant_languages(tenant.id, req)
    return ApiResponse(
        message="Tenant language settings updated successfully",
        data=updated,
    )


@router.get("/bots/{bot_id}/locale", response_model=ApiResponse[dict[str, str]], status_code=status.HTTP_200_OK)
async def get_bot_default_locale(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    loc = await service.get_bot_default_locale(bot_id)
    return ApiResponse(
        message="Bot default locale retrieved",
        data={"bot_id": str(bot_id), "default_locale": loc},
    )


@router.put("/bots/{bot_id}/locale", response_model=ApiResponse[dict[str, str]], status_code=status.HTTP_200_OK)
async def set_bot_default_locale(
    bot_id: UUID,
    req: BotLocaleRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    service = I18nService(db)
    await service.set_bot_default_locale(bot_id, req.locale)
    return ApiResponse(
        message=f"Bot default locale updated to '{req.locale}'",
        data={"bot_id": str(bot_id), "default_locale": req.locale},
    )

