from typing import Any, Optional, Sequence
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import NotFoundError
from modules.message_studio.models import BotMessageTemplate, BotMessageVersion
from modules.message_studio.repository import MessageStudioRepository
from modules.message_studio.schemas import ButtonSchema


class VersionManager:
    """
    Manages template version snapshots, diffing, and rollbacks.
    """

    def __init__(self, db: AsyncSession, repo: Optional[MessageStudioRepository] = None):
        self.db = db
        self.repo = repo or MessageStudioRepository(db)

    @staticmethod
    def create_snapshot_dict(template: BotMessageTemplate) -> dict[str, Any]:
        """Creates a JSON-serializable snapshot of the template state."""
        return {
            "message_key": template.message_key,
            "title": template.title,
            "message_text": template.message_text,
            "parse_mode": template.parse_mode,
            "media_type": template.media_type,
            "media_file_id": template.media_file_id,
            "locale": template.locale,
            "is_active": template.is_active,
            "is_draft": template.is_draft,
            "buttons": [
                {
                    "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 template.buttons
            ],
        }

    async def save_version(
        self,
        template: BotMessageTemplate,
        user_id: Optional[UUID] = None,
    ) -> BotMessageVersion:
        return await self.repo.create_version(template, updated_by=user_id)

    async def list_versions(self, template_id: UUID) -> Sequence[BotMessageVersion]:
        return await self.repo.get_versions(template_id)

    async def rollback(
        self,
        template: BotMessageTemplate,
        target_version: int,
        user_id: Optional[UUID] = None,
    ) -> BotMessageTemplate:
        version_record = await self.repo.get_version(template.id, target_version)
        if not version_record:
            raise NotFoundError(f"Version {target_version} does not exist for template {template.id}")

        snapshot = version_record.snapshot_json
        template.title = snapshot.get("title", template.title)
        template.message_text = snapshot["message_text"]
        template.parse_mode = snapshot.get("parse_mode", "HTML")
        template.media_type = snapshot.get("media_type", "none")
        template.media_file_id = snapshot.get("media_file_id")
        template.locale = snapshot.get("locale", template.locale)
        template.is_active = snapshot.get("is_active", True)
        template.is_draft = snapshot.get("is_draft", False)

        buttons_raw = snapshot.get("buttons", [])
        buttons = [ButtonSchema(**b) for b in buttons_raw]
        await self.repo.replace_buttons(template.id, buttons)

        template_id = template.id
        tenant_id = template.tenant_id

        template.current_version += 1
        await self.db.flush()
        self.db.expire(template)

        # Re-fetch template with new button relationships
        updated = await self.repo.get_by_id(template_id, tenant_id)
        if not updated:
            raise NotFoundError("Template lost during rollback")

        # Record new version for the rollback action
        await self.repo.create_version(updated, updated_by=user_id)
        return updated
