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 core.exceptions import ValidationError
from infrastructure.database.session import get_db
from modules.identity.models import User
from modules.tenants.models import Tenant, TenantMember
from modules.message_studio.schemas import (
    MessageTemplateCreate,
    MessageTemplateUpdate,
    MessageTemplateResponse,
    MessageVersionResponse,
    PreviewRequest,
    PreviewResponse,
    RollbackRequest,
    DuplicateRequest,
    PresetResponse,
    ApplyPresetRequest,
    StyleTextRequest,
    StyleTextResponse,
    GenerateHeaderRequest,
    GenerateHeaderResponse,
    GenerateSeparatorRequest,
    GenerateSeparatorResponse,
    GenerateProgressRequest,
    GenerateProgressResponse,
    ValidateMessageRequest,
    ValidateMessageResponse,
    TemplateExportResponse,
    TemplateImportRequest,
    BotStylingSchema,
)
from modules.message_studio.service import MessageStudioService
from modules.message_studio.unicode_styler import UnicodeStyler
from modules.message_studio.formatter import MessageFormatter
from modules.message_studio.template_engine import TemplateEngine
from modules.message_studio.validators import (
    MessageValidator,
    TELEGRAM_MAX_TEXT_LENGTH,
    TELEGRAM_MAX_CAPTION_LENGTH,
)
from shared.schemas import ApiResponse

# -------------------------------------------------------------
# Bot-Specific Template Operations
# -------------------------------------------------------------
router = APIRouter(prefix="/bots/{bot_id}/messages", tags=["Bot Message Studio"])


@router.get("", response_model=ApiResponse[list[MessageTemplateResponse]], status_code=status.HTTP_200_OK)
async def list_bot_messages(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    locale: Optional[str] = Query(default=None, description="Filter by language code"),
    db: Annotated[AsyncSession, Depends(get_db)] = None,
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    templates = await service.list_templates(bot_id=bot_id, tenant_id=tenant.id, locale=locale)
    return ApiResponse(
        message="Bot message templates retrieved",
        data=[MessageTemplateResponse.model_validate(t) for t in templates],
    )


@router.post("", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_201_CREATED)
async def create_bot_message(
    bot_id: UUID,
    req: MessageTemplateCreate,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.create_template(
        bot_id=bot_id,
        tenant_id=tenant.id,
        data=req,
        user_id=current_user.id,
    )
    return ApiResponse(
        message="Message template created successfully",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.post("/from-preset", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_201_CREATED)
async def create_bot_message_from_preset(
    bot_id: UUID,
    req: ApplyPresetRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.create_from_preset(
        bot_id=bot_id,
        tenant_id=tenant.id,
        req=req,
        user_id=current_user.id,
    )
    return ApiResponse(
        message=f"Template created from preset '{req.preset_key}' successfully",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.get("/export", response_model=ApiResponse[TemplateExportResponse], status_code=status.HTTP_200_OK)
async def export_bot_messages(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    result = await service.export_templates(bot_id=bot_id, tenant_id=tenant.id)
    return ApiResponse(
        message="Bot templates exported successfully",
        data=result,
    )


@router.post("/import", response_model=ApiResponse[list[MessageTemplateResponse]], status_code=status.HTTP_200_OK)
async def import_bot_messages(
    bot_id: UUID,
    req: TemplateImportRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    imported = await service.import_templates(
        bot_id=bot_id,
        tenant_id=tenant.id,
        req=req,
        user_id=current_user.id,
    )
    return ApiResponse(
        message=f"Successfully imported {len(imported)} templates",
        data=[MessageTemplateResponse.model_validate(t) for t in imported],
    )


@router.get("/styling", response_model=ApiResponse[BotStylingSchema], status_code=status.HTTP_200_OK)
async def get_bot_styling(
    bot_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    styling = await service.get_bot_styling(bot_id=bot_id, tenant_id=tenant.id)
    return ApiResponse(
        message="Bot styling settings retrieved",
        data=styling,
    )


@router.put("/styling", response_model=ApiResponse[BotStylingSchema], status_code=status.HTTP_200_OK)
async def update_bot_styling(
    bot_id: UUID,
    styling: BotStylingSchema,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    updated = await service.update_bot_styling(bot_id=bot_id, tenant_id=tenant.id, styling=styling)
    return ApiResponse(
        message="Bot styling settings updated successfully",
        data=updated,
    )



@router.get("/{message_id}", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_200_OK)
async def get_bot_message_details(
    bot_id: UUID,
    message_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.get_template(message_id, tenant.id)
    return ApiResponse(
        message="Message template details retrieved",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.patch("/{message_id}", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_200_OK)
async def update_bot_message(
    bot_id: UUID,
    message_id: UUID,
    req: MessageTemplateUpdate,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.update_template(
        template_id=message_id,
        tenant_id=tenant.id,
        data=req,
        user_id=current_user.id,
    )
    return ApiResponse(
        message="Message template updated successfully",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.delete("/{message_id}", response_model=ApiResponse[None], status_code=status.HTTP_200_OK)
async def delete_bot_message(
    bot_id: UUID,
    message_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    await service.delete_template(template_id=message_id, tenant_id=tenant.id)
    return ApiResponse(
        message="Message template deleted successfully",
        data=None,
    )


@router.post("/{message_id}/preview", response_model=ApiResponse[PreviewResponse], status_code=status.HTTP_200_OK)
async def preview_bot_message(
    bot_id: UUID,
    message_id: UUID,
    req: PreviewRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    preview = await service.preview_template(
        template_id=message_id,
        tenant_id=tenant.id,
        variables=req.variables,
    )
    return ApiResponse(
        message="Message preview rendered successfully",
        data=preview,
    )


@router.post("/{message_id}/publish", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_200_OK)
async def publish_bot_message(
    bot_id: UUID,
    message_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.publish_template(template_id=message_id, tenant_id=tenant.id)
    return ApiResponse(
        message="Message template published and live on bot",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.get("/{message_id}/versions", response_model=ApiResponse[list[MessageVersionResponse]], status_code=status.HTTP_200_OK)
async def get_message_versions(
    bot_id: UUID,
    message_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    await service.get_template(message_id, tenant.id)
    versions = await service.repo.get_versions(message_id)
    return ApiResponse(
        message="Message template versions retrieved",
        data=[MessageVersionResponse.model_validate(v) for v in versions],
    )


@router.post("/{message_id}/rollback", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_200_OK)
async def rollback_bot_message(
    bot_id: UUID,
    message_id: UUID,
    req: RollbackRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    template = await service.rollback_to_version(
        template_id=message_id,
        target_version=req.version,
        tenant_id=tenant.id,
        user_id=current_user.id,
    )
    return ApiResponse(
        message=f"Message template rolled back to version {req.version}",
        data=MessageTemplateResponse.model_validate(template),
    )


@router.post("/{message_id}/duplicate", response_model=ApiResponse[MessageTemplateResponse], status_code=status.HTTP_201_CREATED)
async def duplicate_bot_message(
    bot_id: UUID,
    message_id: UUID,
    req: DuplicateRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    current_user: Annotated[User, Depends(get_current_user)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    tenant, _ = tenant_context
    service = MessageStudioService(db)
    cloned = await service.duplicate_template(
        source_template_id=message_id,
        target_bot_id=req.target_bot_id,
        tenant_id=tenant.id,
        user_id=current_user.id,
    )
    return ApiResponse(
        message=f"Template duplicated successfully to bot {req.target_bot_id}",
        data=MessageTemplateResponse.model_validate(cloned),
    )


# -------------------------------------------------------------
# Advanced Telegram Text Designer & Presets Operations
# -------------------------------------------------------------
designer_router = APIRouter(prefix="/bots/messages", tags=["Advanced Telegram Text Designer"])


@designer_router.get("/presets", response_model=ApiResponse[list[PresetResponse]], status_code=status.HTTP_200_OK)
async def list_design_presets(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    presets = MessageStudioService.list_presets()
    return ApiResponse(
        message="Design presets retrieved successfully",
        data=presets,
    )


@designer_router.get("/presets/{preset_key}", response_model=ApiResponse[PresetResponse], status_code=status.HTTP_200_OK)
async def get_design_preset(
    preset_key: str,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    preset = MessageStudioService.get_preset(preset_key)
    return ApiResponse(
        message=f"Preset '{preset_key}' retrieved successfully",
        data=preset,
    )


@designer_router.post("/designer/style-text", response_model=ApiResponse[StyleTextResponse], status_code=status.HTTP_200_OK)
async def style_unicode_text(
    req: StyleTextRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    styled = UnicodeStyler.style_text(
        text=req.text,
        style=req.style,
        preserve_tags=req.preserve_tags,
        preserve_variables=req.preserve_variables,
    )
    return ApiResponse(
        message="Text styled successfully",
        data=StyleTextResponse(
            original_text=req.text,
            styled_text=styled,
            style=req.style,
        ),
    )


@designer_router.get("/designer/symbols", response_model=ApiResponse[dict[str, list[str]]], status_code=status.HTTP_200_OK)
async def get_unicode_symbols(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    catalog = UnicodeStyler.get_symbol_catalog()
    return ApiResponse(
        message="Unicode symbol catalog retrieved successfully",
        data=catalog,
    )


@designer_router.post("/designer/box", response_model=ApiResponse[GenerateHeaderResponse], status_code=status.HTTP_200_OK)
async def generate_header_box(
    req: GenerateHeaderRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    box = MessageFormatter.build_box(
        title=req.title,
        style=req.style,
        width=req.width,
        bordered=req.bordered,
        auto_small_caps=req.auto_small_caps,
    )
    return ApiResponse(
        message="Header box generated successfully",
        data=GenerateHeaderResponse(header_text=box),
    )


@designer_router.post("/designer/separator", response_model=ApiResponse[GenerateSeparatorResponse], status_code=status.HTTP_200_OK)
async def generate_separator(
    req: GenerateSeparatorRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    separator = MessageFormatter.build_separator(
        preset=req.preset,
        length=req.length,
        custom_char=req.custom_char,
    )
    return ApiResponse(
        message="Separator generated successfully",
        data=GenerateSeparatorResponse(separator_text=separator),
    )


@designer_router.post("/designer/progress", response_model=ApiResponse[GenerateProgressResponse], status_code=status.HTTP_200_OK)
async def generate_progress(
    req: GenerateProgressRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    p_bar = TemplateEngine.generate_progress_bar(
        percent=req.percent,
        length=req.length,
        style=req.style,
    )
    step_hdr = None
    if req.step is not None and req.total_steps is not None:
        step_hdr = TemplateEngine.format_progress_step(
            step=req.step,
            total_steps=req.total_steps,
            title=req.step_title,
        )

    combined = f"{step_hdr}\n{p_bar}" if step_hdr else p_bar

    return ApiResponse(
        message="Progress bar generated successfully",
        data=GenerateProgressResponse(
            progress_bar=p_bar,
            step_header=step_hdr,
            combined=combined,
        ),
    )


@designer_router.post("/designer/validate", response_model=ApiResponse[ValidateMessageResponse], status_code=status.HTTP_200_OK)
async def validate_telegram_message(
    req: ValidateMessageRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
):
    errors: list[str] = []
    text_len = len(req.text)
    max_len = TELEGRAM_MAX_CAPTION_LENGTH if req.media_type != "none" else TELEGRAM_MAX_TEXT_LENGTH

    if req.parse_mode.upper() == "HTML":
        try:
            MessageValidator.validate_html(req.text)
        except ValidationError as e:
            errors.append(str(e.message))

    try:
        MessageValidator.validate_length(req.text, media_type=req.media_type)
    except ValidationError as e:
        errors.append(str(e.message))

    is_valid = len(errors) == 0

    return ApiResponse(
        message="Validation completed",
        data=ValidateMessageResponse(
            is_valid=is_valid,
            length=text_len,
            max_length=max_len,
            errors=errors,
        ),
    )
