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_tenant
from shared.schemas import ApiResponse
from infrastructure.database.session import get_db
from modules.marketplace.schemas import (
    TemplateListItem,
    TemplateDetailResponse,
    CategorySummary,
    MarketplaceModuleItem,
    InstallTemplateRequest,
    UpdateInstanceConfigRequest,
    DeployInstanceRequest,
    InstalledInstanceResponse,
)
from modules.marketplace.service import MarketplaceService
from modules.tenants.models import Tenant, TenantMember

router = APIRouter(prefix="/marketplace", tags=["Universal Bot & AI Marketplace"])


@router.get("/categories", response_model=ApiResponse[list[CategorySummary]], status_code=status.HTTP_200_OK)
async def get_marketplace_categories(
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Returns catalog categories with count of available bots."""
    service = MarketplaceService(db)
    categories = await service.get_categories_summary()
    return ApiResponse(
        message="Marketplace categories retrieved",
        data=categories,
    )


@router.get("/templates", response_model=ApiResponse[list[TemplateListItem]], status_code=status.HTTP_200_OK)
async def list_marketplace_templates(
    db: Annotated[AsyncSession, Depends(get_db)],
    category: Optional[str] = Query(None, description="Filter by category slug"),
    search: Optional[str] = Query(None, description="Search term for name or description"),
    tag: Optional[str] = Query(None, description="Filter by keyword tag"),
    limit: int = Query(50, ge=1, le=100),
    offset: int = Query(0, ge=0),
):
    """Browses the ready-made bot templates catalog."""
    service = MarketplaceService(db)
    templates = await service.list_templates(
        category=category,
        search=search,
        tag=tag,
        limit=limit,
        offset=offset,
    )
    items = [
        TemplateListItem(
            id=t.id,
            name=t.name,
            headline=t.headline,
            category=t.category,
            icon=t.icon,
            version=t.version,
            author=t.author,
            is_official=t.is_official,
            is_featured=t.is_featured,
            rating=t.rating,
            install_count=t.install_count,
            supported_channels=t.supported_channels or [],
            tags=t.tags or [],
        )
        for t in templates
    ]
    return ApiResponse(
        message=f"Retrieved {len(items)} bot blueprints",
        data=items,
    )


@router.get("/templates/{template_id}", response_model=ApiResponse[TemplateDetailResponse], status_code=status.HTTP_200_OK)
async def get_marketplace_template_detail(
    template_id: str,
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Retrieves full specification, manifest, and configuration schema for a bot blueprint."""
    service = MarketplaceService(db)
    t = await service.get_template(template_id)
    detail = TemplateDetailResponse(
        id=t.id,
        name=t.name,
        headline=t.headline,
        description=t.description,
        category=t.category,
        icon=t.icon,
        version=t.version,
        author=t.author,
        is_official=t.is_official,
        is_featured=t.is_featured,
        rating=t.rating,
        install_count=t.install_count,
        supported_channels=t.supported_channels or [],
        required_permissions=t.required_permissions or [],
        config_schema=t.config_schema or {},
        default_config=t.default_config or {},
        system_templates=t.system_templates or [],
        mcp_tools=t.mcp_tools or [],
        modules=t.modules or [],
        tags=t.tags or [],
        manifest=t.manifest or {},
    )
    return ApiResponse(
        message="Bot blueprint specification retrieved",
        data=detail,
    )


@router.get("/modules", response_model=ApiResponse[list[MarketplaceModuleItem]], status_code=status.HTTP_200_OK)
async def list_marketplace_modules(
    db: Annotated[AsyncSession, Depends(get_db)],
    category: Optional[str] = Query(None, description="Filter modules by category"),
):
    """Lists reusable plug-and-play feature modules."""
    service = MarketplaceService(db)
    mods = await service.list_modules(category=category)
    items = [
        MarketplaceModuleItem(
            id=m.id,
            name=m.name,
            description=m.description,
            category=m.category,
            version=m.version,
            icon=m.icon,
            config_schema=m.config_schema or {},
            is_official=m.is_official,
        )
        for m in mods
    ]
    return ApiResponse(
        message="Reusable modules catalog retrieved",
        data=items,
    )


@router.post("/install", response_model=ApiResponse[InstalledInstanceResponse], status_code=status.HTTP_201_CREATED)
async def install_bot_template(
    payload: InstallTemplateRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Installs a ready-made bot blueprint to the current tenant account."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    instance = await service.install_template(tenant.id, payload)
    resp = await service.to_response(instance)
    await db.commit()
    return ApiResponse(
        message=f"Bot '{instance.name}' installed successfully",
        data=resp,
    )


@router.get("/instances", response_model=ApiResponse[list[InstalledInstanceResponse]], status_code=status.HTTP_200_OK)
async def list_installed_instances(
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Lists all bot instances installed in the current tenant."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    instances = await service.list_tenant_instances(tenant.id)
    items = [await service.to_response(inst) for inst in instances]
    return ApiResponse(
        message="Installed bot instances retrieved",
        data=items,
    )


@router.get("/instances/{instance_id}", response_model=ApiResponse[InstalledInstanceResponse], status_code=status.HTTP_200_OK)
async def get_installed_instance(
    instance_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Fetches details of a specific installed bot instance."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    inst = await service.get_instance(instance_id, tenant.id)
    resp = await service.to_response(inst)
    return ApiResponse(
        message="Bot instance details retrieved",
        data=resp,
    )


@router.put("/instances/{instance_id}/config", response_model=ApiResponse[InstalledInstanceResponse], status_code=status.HTTP_200_OK)
async def update_instance_configuration(
    instance_id: UUID,
    payload: UpdateInstanceConfigRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Updates custom configuration, active modules, or MCP tools of an installed bot."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    inst = await service.update_instance_config(instance_id, tenant.id, payload)
    resp = await service.to_response(inst)
    await db.commit()
    return ApiResponse(
        message="Bot configuration updated successfully",
        data=resp,
    )


@router.post("/instances/{instance_id}/deploy", response_model=ApiResponse[InstalledInstanceResponse], status_code=status.HTTP_200_OK)
async def deploy_instance_to_bot(
    instance_id: UUID,
    payload: DeployInstanceRequest,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Deploys and links an installed bot blueprint to an active Telegram Bot on the cloud runtime."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    inst = await service.deploy_instance_to_bot(instance_id, tenant.id, payload.bot_id)
    resp = await service.to_response(inst)
    await db.commit()
    return ApiResponse(
        message=f"Bot '{inst.name}' successfully deployed to cloud runtime",
        data=resp,
    )


@router.delete("/instances/{instance_id}", response_model=ApiResponse[dict[str, bool]], status_code=status.HTTP_200_OK)
async def uninstall_instance(
    instance_id: UUID,
    tenant_context: Annotated[tuple[Tenant, TenantMember | None], Depends(get_current_tenant)],
    db: Annotated[AsyncSession, Depends(get_db)],
):
    """Uninstalls and removes a bot instance from the tenant account."""
    tenant, _ = tenant_context
    service = MarketplaceService(db)
    await service.uninstall_instance(instance_id, tenant.id)
    await db.commit()
    return ApiResponse(
        message="Bot instance uninstalled",
        data={"uninstalled": True},
    )
