from datetime import datetime, timezone
from typing import Any, Optional, Sequence
from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import ConflictError, NotFoundError, ForbiddenError, ValidationError
from core.logging import get_logger
from infrastructure.redis.cache import TenantCache
from modules.bots.models import Bot, BotSetting
from modules.message_studio.models import BotMessageTemplate
from modules.message_studio.repository import MessageStudioRepository
from modules.message_studio.renderer import DEFAULT_SYSTEM_TEMPLATES
from modules.message_studio.variable_resolver import VariableResolver
from modules.message_studio.button_builder import ButtonGridBuilder
from modules.message_studio.validators import MessageValidator
from modules.message_studio.preview_service import PreviewService
from modules.message_studio.version_manager import VersionManager
from modules.message_studio.presets_manager import PresetManager
from modules.message_studio.schemas import (
    ButtonSchema,
    MessageTemplateCreate,
    MessageTemplateUpdate,
    MessageTemplateResponse,
    PreviewResponse,
    PresetResponse,
    ApplyPresetRequest,
    TemplateExportResponse,
    TemplateImportRequest,
    BotStylingSchema,
)

logger = get_logger(__name__)


class MessageStudioService:
    def __init__(self, db: AsyncSession):
        self.db = db
        self.repo = MessageStudioRepository(db)
        self.version_mgr = VersionManager(db, self.repo)

    @classmethod
    def _cache_key(cls, bot_id: UUID, message_key: str, locale: str) -> str:
        return f"template:{bot_id}:{message_key}:{locale}"

    async def _invalidate_cache(self, bot_id: UUID, message_key: str, locale: str) -> None:
        try:
            await TenantCache.delete(self._cache_key(bot_id, message_key, locale))
        except Exception as exc:
            logger.warning("cache_invalidation_failed", error=str(exc))

    async def list_templates(
        self,
        bot_id: UUID,
        tenant_id: UUID,
        locale: Optional[str] = None,
    ) -> Sequence[BotMessageTemplate]:
        return await self.repo.list_by_bot(bot_id=bot_id, tenant_id=tenant_id, locale=locale)

    async def get_template(self, template_id: UUID, tenant_id: UUID) -> BotMessageTemplate:
        template = await self.repo.get_by_id(template_id, tenant_id)
        if not template:
            raise NotFoundError("Message template not found")
        return template

    async def create_template(
        self,
        bot_id: UUID,
        tenant_id: UUID,
        data: MessageTemplateCreate,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        # 1. Verify bot belongs to tenant
        stmt = select(Bot).where(Bot.id == bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        if not res.scalar_one_or_none():
            raise ForbiddenError("Bot does not belong to this workspace")

        # 2. Validate template contents
        if data.parse_mode.upper() == "HTML":
            MessageValidator.validate_html(data.message_text)
        MessageValidator.validate_length(data.message_text, media_type=data.media_type)

        existing = await self.repo.get_by_key(
            bot_id=bot_id,
            message_key=data.message_key,
            locale=data.locale,
        )
        if existing:
            raise ConflictError(
                f"Template with key '{data.message_key}' already exists for locale '{data.locale}' on this bot"
            )

        template = BotMessageTemplate(
            tenant_id=tenant_id,
            bot_id=bot_id,
            message_key=data.message_key,
            title=data.title,
            message_text=data.message_text,
            parse_mode=data.parse_mode,
            media_type=data.media_type,
            media_file_id=data.media_file_id,
            locale=data.locale,
            is_active=data.is_active,
            is_draft=data.is_draft,
            current_version=1,
        )
        await self.repo.create_template(template)

        # Attach buttons
        template_id = template.id
        if data.buttons:
            await self.repo.replace_buttons(template_id, data.buttons)

        # Refresh template with buttons
        self.db.expire(template)
        template = await self.get_template(template_id, tenant_id)

        # Create Version 1 Snapshot
        await self.repo.create_version(template, updated_by=user_id)
        await self._invalidate_cache(bot_id, data.message_key, data.locale)

        return template

    async def update_template(
        self,
        template_id: UUID,
        tenant_id: UUID,
        data: MessageTemplateUpdate,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        template = await self.get_template(template_id, tenant_id)

        target_text = data.message_text if data.message_text is not None else template.message_text
        target_parse_mode = data.parse_mode if data.parse_mode is not None else template.parse_mode
        target_media_type = data.media_type if data.media_type is not None else template.media_type

        # Validate if text or parse mode updated
        if target_parse_mode.upper() == "HTML":
            MessageValidator.validate_html(target_text)
        MessageValidator.validate_length(target_text, media_type=target_media_type)

        if data.title is not None:
            template.title = data.title
        if data.message_text is not None:
            template.message_text = data.message_text
        if data.parse_mode is not None:
            template.parse_mode = data.parse_mode
        if data.media_type is not None:
            template.media_type = data.media_type
        if data.media_file_id is not None:
            template.media_file_id = data.media_file_id
        if data.locale is not None:
            template.locale = data.locale
        if data.is_active is not None:
            template.is_active = data.is_active
        if data.is_draft is not None:
            template.is_draft = data.is_draft

        # Update buttons if provided
        if data.buttons is not None:
            await self.repo.replace_buttons(template.id, data.buttons)

        # Bump version and snapshot
        template.current_version += 1
        await self.db.flush()
        self.db.expire(template)

        # Refresh
        template = await self.get_template(template_id, tenant_id)
        await self.repo.create_version(template, updated_by=user_id)
        await self._invalidate_cache(template.bot_id, template.message_key, template.locale)

        return template

    async def publish_template(self, template_id: UUID, tenant_id: UUID) -> BotMessageTemplate:
        template = await self.get_template(template_id, tenant_id)
        template.is_draft = False
        template.is_active = True
        await self.db.flush()
        await self._invalidate_cache(template.bot_id, template.message_key, template.locale)
        return template

    async def delete_template(self, template_id: UUID, tenant_id: UUID) -> None:
        template = await self.get_template(template_id, tenant_id)
        bot_id = template.bot_id
        key = template.message_key
        loc = template.locale

        await self.repo.delete_template(template)
        await self._invalidate_cache(bot_id, key, loc)

    async def rollback_to_version(
        self,
        template_id: UUID,
        target_version: int,
        tenant_id: UUID,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        template = await self.get_template(template_id, tenant_id)
        updated = await self.version_mgr.rollback(template, target_version, user_id=user_id)
        await self._invalidate_cache(updated.bot_id, updated.message_key, updated.locale)
        return updated

    async def duplicate_template(
        self,
        source_template_id: UUID,
        target_bot_id: UUID,
        tenant_id: UUID,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        source = await self.get_template(source_template_id, tenant_id)

        # Check target bot belongs to tenant
        stmt = select(Bot).where(Bot.id == target_bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        if not res.scalar_one_or_none():
            raise ForbiddenError("Target bot does not belong to your workspace")

        existing = await self.repo.get_by_key(
            bot_id=target_bot_id,
            message_key=source.message_key,
            locale=source.locale,
        )
        if existing:
            raise ConflictError(
                f"Target bot already has a template for key '{source.message_key}' in locale '{source.locale}'"
            )

        cloned_buttons = [
            ButtonSchema(
                text=b.text,
                button_type=b.button_type,
                action_value=b.action_value,
                row_position=b.row_position,
                column_position=b.column_position,
                sort_order=b.sort_order,
            )
            for b in source.buttons
        ]

        create_data = MessageTemplateCreate(
            message_key=source.message_key,
            title=f"{source.title} (Copy)",
            message_text=source.message_text,
            parse_mode=source.parse_mode,
            media_type=source.media_type,
            media_file_id=source.media_file_id,
            locale=source.locale,
            is_active=source.is_active,
            is_draft=source.is_draft,
            buttons=cloned_buttons,
        )

        return await self.create_template(
            bot_id=target_bot_id,
            tenant_id=tenant_id,
            data=create_data,
            user_id=user_id,
        )

    async def preview_template(
        self,
        template_id: UUID,
        tenant_id: UUID,
        variables: Optional[dict[str, Any]] = None,
    ) -> PreviewResponse:
        template = await self.get_template(template_id, tenant_id)
        return PreviewService.preview_template(template, variables=variables)

    async def create_from_preset(
        self,
        bot_id: UUID,
        tenant_id: UUID,
        req: ApplyPresetRequest,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        preset = PresetManager.get_preset(req.preset_key)
        target_key = req.message_key or preset.key
        target_title = req.title or preset.title

        create_data = MessageTemplateCreate(
            message_key=target_key,
            title=target_title,
            message_text=preset.message_text,
            parse_mode=preset.parse_mode,  # type: ignore[arg-type]
            media_type=preset.media_type,  # type: ignore[arg-type]
            media_file_id=preset.media_file_id,
            locale=req.locale,
            is_active=True,
            is_draft=False,
            buttons=preset.buttons,
        )

        return await self.create_template(
            bot_id=bot_id,
            tenant_id=tenant_id,
            data=create_data,
            user_id=user_id,
        )

    @classmethod
    def list_presets(cls) -> list[PresetResponse]:
        return PresetManager.list_presets()

    @classmethod
    def get_preset(cls, key: str) -> PresetResponse:
        return PresetManager.get_preset(key)

    async def export_templates(
        self,
        bot_id: UUID,
        tenant_id: UUID,
    ) -> TemplateExportResponse:
        stmt = select(Bot).where(Bot.id == bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        if not res.scalar_one_or_none():
            raise ForbiddenError("Bot does not belong to this workspace")

        templates = await self.repo.list_by_bot(bot_id=bot_id, tenant_id=tenant_id)
        template_responses = [
            MessageTemplateResponse.model_validate(t)
            for t in templates
        ]
        return TemplateExportResponse(
            bot_id=bot_id,
            exported_at=datetime.now(timezone.utc),
            version="1.0",
            templates=template_responses,
        )

    async def import_templates(
        self,
        bot_id: UUID,
        tenant_id: UUID,
        req: TemplateImportRequest,
        user_id: Optional[UUID] = None,
    ) -> list[BotMessageTemplate]:
        stmt = select(Bot).where(Bot.id == bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        if not res.scalar_one_or_none():
            raise ForbiddenError("Bot does not belong to this workspace")

        imported: list[BotMessageTemplate] = []
        for item in req.templates:
            existing = await self.repo.get_by_key(
                bot_id=bot_id,
                message_key=item.message_key,
                locale=item.locale,
            )
            if existing:
                if req.overwrite:
                    update_data = MessageTemplateUpdate(
                        title=item.title,
                        message_text=item.message_text,
                        parse_mode=item.parse_mode,
                        media_type=item.media_type,
                        media_file_id=item.media_file_id,
                        locale=item.locale,
                        is_active=item.is_active,
                        is_draft=False,
                        buttons=item.buttons,
                    )
                    tmpl = await self.update_template(
                        template_id=existing.id,
                        tenant_id=tenant_id,
                        data=update_data,
                        user_id=user_id,
                    )
                    imported.append(tmpl)
                else:
                    imported.append(existing)
            else:
                create_data = MessageTemplateCreate(
                    message_key=item.message_key,
                    title=item.title,
                    message_text=item.message_text,
                    parse_mode=item.parse_mode,
                    media_type=item.media_type,
                    media_file_id=item.media_file_id,
                    locale=item.locale,
                    is_active=item.is_active,
                    is_draft=False,
                    buttons=item.buttons,
                )
                tmpl = await self.create_template(
                    bot_id=bot_id,
                    tenant_id=tenant_id,
                    data=create_data,
                    user_id=user_id,
                )
                imported.append(tmpl)
        return imported

    async def get_bot_styling(self, bot_id: UUID, tenant_id: UUID) -> BotStylingSchema:
        stmt = select(Bot).where(Bot.id == bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        bot = res.scalar_one_or_none()
        if not bot:
            raise NotFoundError("Bot not found or does not belong to this workspace")

        if bot.settings and bot.settings.settings_json:
            styling_dict = bot.settings.settings_json.get("styling")
            if styling_dict and isinstance(styling_dict, dict):
                try:
                    return BotStylingSchema.model_validate(styling_dict)
                except Exception:
                    pass
        return BotStylingSchema()

    async def update_bot_styling(
        self,
        bot_id: UUID,
        tenant_id: UUID,
        styling: BotStylingSchema,
    ) -> BotStylingSchema:
        stmt = select(Bot).where(Bot.id == bot_id, Bot.tenant_id == tenant_id)
        res = await self.db.execute(stmt)
        bot = res.scalar_one_or_none()
        if not bot:
            raise NotFoundError("Bot not found or does not belong to this workspace")

        if not bot.settings:
            bot.settings = BotSetting(bot_id=bot.id, settings_json={})
            self.db.add(bot.settings)
            await self.db.flush()

        current_settings = dict(bot.settings.settings_json or {})
        current_settings["styling"] = styling.model_dump()
        bot.settings.settings_json = current_settings
        await self.db.flush()
        return styling

    async def get_rendered_message(
        self,
        bot_id: UUID,
        message_key: str,
        context: Optional[dict[str, Any]] = None,
        locale: str = "en",
    ) -> dict[str, Any]:
        """
        Fast runtime helper for Telegram bot engine.
        Returns dictionary with text, aiogram keyboard, media info, and parse mode.
        """
        # 1. Lookup custom template for this bot
        template = await self.repo.get_by_key(bot_id=bot_id, message_key=message_key, locale=locale)

        # Fallback to English if localized template is missing
        if not template and locale != "en":
            template = await self.repo.get_by_key(bot_id=bot_id, message_key=message_key, locale="en")

        if template and template.is_active and not template.is_draft:
            rendered_text = VariableResolver.resolve(template.message_text, context)
            aiogram_kb = ButtonGridBuilder.to_aiogram(template.buttons)
            return {
                "text": rendered_text,
                "keyboard": aiogram_kb,
                "media_type": template.media_type,
                "media_file_id": template.media_file_id,
                "parse_mode": template.parse_mode,
            }

        # 2. Check localized string from i18n catalog if locale is non-English
        if locale != "en":
            from modules.i18n.repository import TranslationRepository
            loc_strings = TranslationRepository.load_file_translations(locale, "bot")
            localized_msg = loc_strings.get(message_key)
            if localized_msg:
                rendered_text = VariableResolver.resolve(localized_msg, context)
                sys_default = DEFAULT_SYSTEM_TEMPLATES.get(message_key)
                aiogram_kb = ButtonGridBuilder.to_aiogram(sys_default["buttons"]) if sys_default else None
                return {
                    "text": rendered_text,
                    "keyboard": aiogram_kb,
                    "media_type": sys_default["media_type"] if sys_default else "none",
                    "media_file_id": sys_default["media_file_id"] if sys_default else None,
                    "parse_mode": sys_default["parse_mode"] if sys_default else "HTML",
                }

        # 3. System Default Template Fallback
        sys_default = DEFAULT_SYSTEM_TEMPLATES.get(message_key)
        if sys_default:
            rendered_text = VariableResolver.resolve(sys_default["message_text"], context)
            aiogram_kb = ButtonGridBuilder.to_aiogram(sys_default["buttons"])
            return {
                "text": rendered_text,
                "keyboard": aiogram_kb,
                "media_type": sys_default["media_type"],
                "media_file_id": sys_default["media_file_id"],
                "parse_mode": sys_default["parse_mode"],
            }

        # 3. Simple Fallback
        return {
            "text": f"[{message_key.upper()}]",
            "keyboard": None,
            "media_type": "none",
            "media_file_id": None,
            "parse_mode": "HTML",
        }
