import uuid
from datetime import datetime, timezone
from typing import Any, Optional, Sequence
from sqlalchemy.ext.asyncio import AsyncSession
from core.exceptions import NotFoundError, ValidationError, ForbiddenError
from modules.marketplace.models import InstalledBotInstance, MarketplaceTemplate, MarketplaceModule
from modules.marketplace.repository import MarketplaceRepository
from modules.marketplace.schemas import (
    InstallTemplateRequest,
    UpdateInstanceConfigRequest,
    CategorySummary,
    InstalledInstanceResponse,
)
from modules.bots.models import Bot
from modules.bots.modular_engine import BotModuleService


CATEGORY_METADATA = [
    {
        "slug": "all",
        "title": "All Blueprints",
        "description": "Explore the complete library of verified production bots.",
        "icon": "layout-grid",
    },
    {
        "slug": "business",
        "title": "Business & Monetization",
        "description": "E-commerce stores, paid VIP channels, appointment bookings & CRM funnels.",
        "icon": "briefcase",
    },
    {
        "slug": "community",
        "title": "Community & Moderation",
        "description": "Anti-spam shields, captcha gates, group admin governance & viral referrals.",
        "icon": "users",
    },
    {
        "slug": "ai_specialist",
        "title": "AI Agents & Specialists",
        "description": "ChatGPT personas, PDF research analysts, RAG knowledge bases & image studios.",
        "icon": "sparkles",
    },
    {
        "slug": "developer_tools",
        "title": "Developer & DevOps",
        "description": "GitHub CI/CD notifiers, uptime monitoring, webhooks & SQL reporting bots.",
        "icon": "terminal",
    },
    {
        "slug": "content_media",
        "title": "Content & Automation",
        "description": "RSS auto-publishers, news summarizers, watermark processors & feed schedulers.",
        "icon": "newspaper",
    },
]


class MarketplaceService:
    def __init__(self, session: AsyncSession):
        self.session = session
        self.repo = MarketplaceRepository(session)

    async def ensure_seeded(self) -> int:
        return await self.repo.seed_defaults_if_empty()

    async def list_templates(
        self,
        category: Optional[str] = None,
        search: Optional[str] = None,
        tag: Optional[str] = None,
        limit: int = 50,
        offset: int = 0,
    ) -> Sequence[MarketplaceTemplate]:
        await self.ensure_seeded()
        return await self.repo.list_templates(
            category=category,
            search=search,
            tag=tag,
            limit=limit,
            offset=offset,
        )

    async def get_template(self, template_id: str) -> MarketplaceTemplate:
        await self.ensure_seeded()
        template = await self.repo.get_template_by_id(template_id)
        if not template:
            raise NotFoundError(f"Marketplace template '{template_id}' was not found.")
        return template

    async def get_categories_summary(self) -> list[CategorySummary]:
        await self.ensure_seeded()
        counts = await self.repo.count_by_categories()
        total_count = sum(counts.values())

        summaries: list[CategorySummary] = []
        for cat in CATEGORY_METADATA:
            if cat["slug"] == "all":
                count = total_count
            else:
                count = counts.get(cat["slug"], 0)
            summaries.append(
                CategorySummary(
                    slug=cat["slug"],
                    title=cat["title"],
                    description=cat["description"],
                    icon=cat["icon"],
                    count=count,
                )
            )
        return summaries

    async def list_modules(self, category: Optional[str] = None) -> Sequence[MarketplaceModule]:
        await self.ensure_seeded()
        return await self.repo.list_modules(category=category)

    async def install_template(
        self,
        tenant_id: uuid.UUID,
        data: InstallTemplateRequest,
    ) -> InstalledBotInstance:
        template = await self.get_template(data.template_id)

        # Merge defaults with custom values
        final_config = dict(template.default_config or {})
        if data.custom_config:
            final_config.update(data.custom_config)

        # Module defaults
        enabled_modules = data.enabled_modules
        if enabled_modules is None:
            enabled_modules = [m["id"] for m in (template.modules or [])]

        # MCP tools defaults
        enabled_mcp_tools = data.enabled_mcp_tools
        if enabled_mcp_tools is None:
            enabled_mcp_tools = list(template.mcp_tools or [])

        # Validate optional bot_id if passed
        if data.bot_id:
            bot = await self.session.get(Bot, data.bot_id)
            if not bot or bot.tenant_id != tenant_id:
                raise ValidationError("Selected bot does not exist or does not belong to your tenant.")

        instance = InstalledBotInstance(
            tenant_id=tenant_id,
            template_id=template.id,
            bot_id=data.bot_id,
            name=data.name or template.name,
            version_installed=template.version,
            status="deployed" if data.bot_id else "configured",
            custom_config=final_config,
            installed_modules=enabled_modules,
            enabled_mcp_tools=enabled_mcp_tools,
            last_deployed_at=datetime.now(timezone.utc) if data.bot_id else None,
            health_status="healthy",
            metrics={
                "total_interactions": 0,
                "active_users": 0,
                "uptime_pct": 100.0,
            },
        )

        instance = await self.repo.create_instance(instance)
        await self.repo.increment_install_count(template.id)

        # If bound to a live bot, automatically configure and activate the template's modules
        if data.bot_id:
            try:
                mod_svc = BotModuleService(self.session)
                manifest_dict = {
                    "category": template.category,
                    "modules": template.modules or [],
                    "default_config": template.default_config or {},
                }
                await mod_svc.apply_template_to_bot(data.bot_id, template.id, manifest_dict)
            except Exception as apply_err:
                # Log non-fatal template module provisioning issue
                pass

        return instance

    async def list_tenant_instances(self, tenant_id: uuid.UUID) -> Sequence[InstalledBotInstance]:
        return await self.repo.list_instances_by_tenant(tenant_id)

    async def get_instance(
        self, instance_id: uuid.UUID, tenant_id: uuid.UUID
    ) -> InstalledBotInstance:
        instance = await self.repo.get_instance_by_id(instance_id, tenant_id)
        if not instance:
            raise NotFoundError(f"Installed bot instance '{instance_id}' not found.")
        return instance

    async def update_instance_config(
        self,
        instance_id: uuid.UUID,
        tenant_id: uuid.UUID,
        data: UpdateInstanceConfigRequest,
    ) -> InstalledBotInstance:
        instance = await self.get_instance(instance_id, tenant_id)

        if data.name:
            instance.name = data.name

        # Merge config
        current_config = dict(instance.custom_config or {})
        current_config.update(data.custom_config)
        instance.custom_config = current_config

        if data.enabled_modules is not None:
            instance.installed_modules = data.enabled_modules

        if data.enabled_mcp_tools is not None:
            instance.enabled_mcp_tools = data.enabled_mcp_tools

        await self.session.flush()
        return instance

    async def deploy_instance_to_bot(
        self,
        instance_id: uuid.UUID,
        tenant_id: uuid.UUID,
        bot_id: uuid.UUID,
    ) -> InstalledBotInstance:
        instance = await self.get_instance(instance_id, tenant_id)

        # Validate bot
        bot = await self.session.get(Bot, bot_id)
        if not bot or bot.tenant_id != tenant_id:
            raise ValidationError("Target bot does not exist or does not belong to your tenant.")

        instance.bot_id = bot.id
        instance.status = "deployed"
        instance.health_status = "healthy"
        instance.last_deployed_at = datetime.now(timezone.utc)

        await self.session.flush()
        return instance

    async def uninstall_instance(
        self, instance_id: uuid.UUID, tenant_id: uuid.UUID
    ) -> None:
        instance = await self.get_instance(instance_id, tenant_id)
        await self.repo.delete_instance(instance)

    async def to_response(
        self,
        instance: InstalledBotInstance,
        template: Optional[MarketplaceTemplate] = None,
    ) -> InstalledInstanceResponse:
        if not template:
            template = await self.repo.get_template_by_id(instance.template_id)
        return InstalledInstanceResponse(
            id=instance.id,
            tenant_id=instance.tenant_id,
            template_id=instance.template_id,
            bot_id=instance.bot_id,
            name=instance.name,
            version_installed=instance.version_installed,
            status=instance.status,
            custom_config=instance.custom_config or {},
            installed_modules=instance.installed_modules or [],
            enabled_mcp_tools=instance.enabled_mcp_tools or [],
            last_deployed_at=instance.last_deployed_at,
            health_status=instance.health_status,
            metrics=instance.metrics or {},
            created_at=instance.created_at,
            updated_at=instance.updated_at,
            template_name=template.name if template else instance.name,
            template_category=template.category if template else None,
            template_icon=template.icon if template else "bot",
        )
