"""
Chatbot Management API

Dedicated endpoints for managing chatbot agents, connectors, knowledge base,
human handoff, and analytics - distinct from the proxy routes.

These endpoints manage configurations stored in central-backend and
coordinate with chatbot-service for operational tasks.
"""
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, delete
from typing import List, Optional
from pydantic import BaseModel, Field
from enum import Enum
from datetime import datetime
import httpx
import json
import structlog

from app.database import get_db
from app.auth.dependencies import get_current_user, require_permissions
from app.models.user import User
from app.models.service_config import ServiceConfig, ServiceCredential, ServiceType
from app.config import settings

logger = structlog.get_logger()
router = APIRouter()


# ==================== SCHEMAS ====================

class AgentType(str, Enum):
    """Supported agent types"""
    ECOMMERCE = "ecommerce"
    POS = "pos"
    RESTAURANT = "restaurant"
    HEALTHCARE = "healthcare"
    MANUFACTURING = "manufacturing"
    CRM = "crm"
    ERP = "erp"
    REAL_ESTATE = "real_estate"
    HOSPITALITY = "hospitality"
    EDUCATION = "education"
    CUSTOM = "custom"


class ConnectorType(str, Enum):
    """Supported connector types"""
    CUSTOM_API = "custom_api"
    CUSTOM_DATABASE = "custom_database"
    SHOPIFY = "shopify"
    WOOCOMMERCE = "woocommerce"
    MAGENTO = "magento"
    SALESFORCE = "salesforce"
    ZOHO = "zoho"


class AgentConfigCreate(BaseModel):
    """Create/Update agent configuration"""
    agent_type: AgentType
    agent_name: str = Field(..., min_length=2, max_length=100)
    welcome_message: str = "Hello! How can I help you today?"
    fallback_message: str = "I'm sorry, I couldn't understand that. Could you please rephrase?"
    system_prompt: Optional[str] = None
    tone: str = "professional"  # professional, friendly, casual
    language: str = "en"
    supported_languages: List[str] = ["en"]
    enabled_tools: List[str] = []  # List of tool names to enable
    business_rules: dict = {}  # Custom business rules
    branding: dict = {}  # Colors, logo, avatar


class AgentConfigResponse(BaseModel):
    """Agent configuration response"""
    client_id: int
    agent_type: str
    agent_name: str
    welcome_message: str
    fallback_message: str
    system_prompt: Optional[str]
    tone: str
    language: str
    supported_languages: List[str]
    enabled_tools: List[str]
    business_rules: dict
    branding: dict
    is_active: bool
    created_at: datetime
    updated_at: datetime


class ConnectorConfigCreate(BaseModel):
    """Create connector configuration"""
    connector_type: ConnectorType
    name: str = Field(..., min_length=2, max_length=100)

    # For Custom API
    base_url: Optional[str] = None
    auth_type: Optional[str] = None  # bearer, basic, api_key
    auth_credentials: Optional[dict] = None
    endpoint_mappings: Optional[dict] = None
    field_mappings: Optional[dict] = None

    # For Custom Database
    db_type: Optional[str] = None  # mysql, postgresql, sqlserver
    db_host: Optional[str] = None
    db_port: Optional[int] = None
    db_name: Optional[str] = None
    db_user: Optional[str] = None
    db_password: Optional[str] = None
    query_mappings: Optional[dict] = None

    # For Platform connectors (Shopify, WooCommerce, etc.)
    api_key: Optional[str] = None
    api_secret: Optional[str] = None
    store_url: Optional[str] = None

    is_active: bool = True


class ConnectorConfigResponse(BaseModel):
    """Connector configuration response"""
    id: int
    client_id: int
    connector_type: str
    name: str
    is_active: bool
    is_verified: bool
    last_verified_at: Optional[datetime]
    created_at: datetime


class KnowledgeDocumentCreate(BaseModel):
    """Upload knowledge document"""
    name: str
    description: Optional[str] = None
    document_type: str = "general"  # general, faq, policy, product


class HandoffAgentCreate(BaseModel):
    """Create human handoff agent"""
    name: str
    email: str
    phone: Optional[str] = None
    max_conversations: int = 5
    skills: List[str] = []
    languages: List[str] = ["en"]


class HandoffConfigUpdate(BaseModel):
    """Update handoff configuration"""
    enabled: bool = True
    handoff_keywords: List[str] = ["speak to human", "talk to agent"]
    negative_sentiment_threshold: float = 0.3
    max_ai_failures: int = 3
    high_value_threshold: float = 100000
    business_hours: dict = {
        "timezone": "Asia/Kolkata",
        "start": "09:00",
        "end": "18:00",
        "days": [0, 1, 2, 3, 4, 5]
    }
    handoff_message: str = "I'm connecting you with a representative..."
    no_agent_message: str = "Our team is currently unavailable..."


# ==================== AGENT CONFIGURATION ====================

@router.get("/agent", response_model=AgentConfigResponse)
async def get_agent_config(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get current agent configuration"""
    query = select(ServiceConfig).where(
        ServiceConfig.client_id == current_user.client_id,
        ServiceConfig.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    config = result.scalar_one_or_none()

    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Agent configuration not found. Please configure your agent first."
        )

    settings_data = config.settings or {}
    branding_data = config.branding or {}

    return AgentConfigResponse(
        client_id=config.client_id,
        agent_type=settings_data.get("agent_type", "custom"),
        agent_name=branding_data.get("bot_name", "AI Assistant"),
        welcome_message=settings_data.get("welcome_message", "Hello!"),
        fallback_message=settings_data.get("fallback_message", "Sorry, I couldn't understand."),
        system_prompt=settings_data.get("system_prompt"),
        tone=settings_data.get("tone", "professional"),
        language=settings_data.get("language", "en"),
        supported_languages=settings_data.get("supported_languages", ["en"]),
        enabled_tools=settings_data.get("enabled_tools", []),
        business_rules=settings_data.get("business_rules", {}),
        branding=branding_data,
        is_active=config.is_active,
        created_at=config.created_at,
        updated_at=config.updated_at
    )


@router.post("/agent", response_model=AgentConfigResponse)
async def create_agent_config(
    config_data: AgentConfigCreate,
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Create or update agent configuration"""
    # Check if config exists
    query = select(ServiceConfig).where(
        ServiceConfig.client_id == current_user.client_id,
        ServiceConfig.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    existing_config = result.scalar_one_or_none()

    settings_data = {
        "agent_type": config_data.agent_type.value,
        "welcome_message": config_data.welcome_message,
        "fallback_message": config_data.fallback_message,
        "system_prompt": config_data.system_prompt or _get_default_system_prompt(config_data.agent_type),
        "tone": config_data.tone,
        "language": config_data.language,
        "supported_languages": config_data.supported_languages,
        "enabled_tools": config_data.enabled_tools or _get_default_tools(config_data.agent_type),
        "business_rules": config_data.business_rules,
    }

    branding_data = {
        "bot_name": config_data.agent_name,
        **config_data.branding
    }

    if existing_config:
        # Update existing
        existing_config.settings = {**existing_config.settings, **settings_data}
        existing_config.branding = {**existing_config.branding, **branding_data}
        existing_config.updated_at = datetime.utcnow()
        await db.commit()
        await db.refresh(existing_config)
        config = existing_config
    else:
        # Create new
        config = ServiceConfig(
            client_id=current_user.client_id,
            service_type=ServiceType.CHATBOT,
            is_enabled=True,
            is_active=True,
            ai_provider="openai",
            ai_model="gpt-4",
            settings=settings_data,
            branding=branding_data
        )
        db.add(config)
        await db.commit()
        await db.refresh(config)

    # Notify chatbot service about config change
    await _notify_chatbot_service(
        current_user.client_id,
        "config_updated",
        {"agent_type": config_data.agent_type.value}
    )

    return AgentConfigResponse(
        client_id=config.client_id,
        agent_type=settings_data["agent_type"],
        agent_name=branding_data["bot_name"],
        welcome_message=settings_data["welcome_message"],
        fallback_message=settings_data["fallback_message"],
        system_prompt=settings_data["system_prompt"],
        tone=settings_data["tone"],
        language=settings_data["language"],
        supported_languages=settings_data["supported_languages"],
        enabled_tools=settings_data["enabled_tools"],
        business_rules=settings_data["business_rules"],
        branding=branding_data,
        is_active=config.is_active,
        created_at=config.created_at,
        updated_at=config.updated_at
    )


@router.get("/agent/tools")
async def get_available_tools(
    agent_type: Optional[AgentType] = None,
    current_user: User = Depends(require_permissions("chatbot:read"))
):
    """Get list of available tools for agent type"""
    # Core tools available to all agents
    core_tools = [
        {"name": "get_sales", "category": "sales", "description": "Get sales data"},
        {"name": "get_orders", "category": "orders", "description": "Get order list"},
        {"name": "get_order_details", "category": "orders", "description": "Get order details"},
        {"name": "get_products", "category": "products", "description": "Get product list"},
        {"name": "get_inventory", "category": "inventory", "description": "Get inventory status"},
        {"name": "get_customers", "category": "customers", "description": "Get customer list"},
    ]

    # Agent-specific tools
    specialized_tools = {
        AgentType.RESTAURANT: [
            {"name": "get_reservations", "category": "restaurant", "description": "Get reservations"},
            {"name": "create_reservation", "category": "restaurant", "description": "Create reservation"},
            {"name": "get_tables", "category": "restaurant", "description": "Get table status"},
            {"name": "get_menu", "category": "restaurant", "description": "Get menu items"},
            {"name": "get_kitchen_orders", "category": "restaurant", "description": "Get kitchen orders"},
        ],
        AgentType.HEALTHCARE: [
            {"name": "get_patients", "category": "healthcare", "description": "Get patient list"},
            {"name": "get_appointments", "category": "healthcare", "description": "Get appointments"},
            {"name": "create_appointment", "category": "healthcare", "description": "Book appointment"},
            {"name": "get_prescriptions", "category": "healthcare", "description": "Get prescriptions"},
            {"name": "get_doctor_schedule", "category": "healthcare", "description": "Get doctor availability"},
        ],
        AgentType.REAL_ESTATE: [
            {"name": "search_properties", "category": "real_estate", "description": "Search properties"},
            {"name": "get_property_details", "category": "real_estate", "description": "Get property details"},
            {"name": "schedule_property_tour", "category": "real_estate", "description": "Schedule viewing"},
            {"name": "create_property_lead", "category": "real_estate", "description": "Create lead"},
            {"name": "calculate_emi", "category": "real_estate", "description": "Calculate EMI"},
        ],
        AgentType.CRM: [
            {"name": "get_contacts", "category": "crm", "description": "Get contacts"},
            {"name": "get_deals", "category": "crm", "description": "Get deals"},
            {"name": "get_pipeline_summary", "category": "crm", "description": "Get pipeline"},
            {"name": "create_activity", "category": "crm", "description": "Log activity"},
        ],
        AgentType.ERP: [
            {"name": "get_purchase_orders", "category": "erp", "description": "Get POs"},
            {"name": "get_suppliers", "category": "erp", "description": "Get suppliers"},
            {"name": "get_accounts_payable", "category": "erp", "description": "Get payables"},
            {"name": "get_financial_summary", "category": "erp", "description": "Get financials"},
        ],
        AgentType.MANUFACTURING: [
            {"name": "get_production_orders", "category": "manufacturing", "description": "Get production orders"},
            {"name": "get_machine_status", "category": "manufacturing", "description": "Get machine status"},
            {"name": "get_quality_reports", "category": "manufacturing", "description": "Get QC reports"},
        ],
    }

    result = {
        "core_tools": core_tools,
        "specialized_tools": []
    }

    if agent_type and agent_type in specialized_tools:
        result["specialized_tools"] = specialized_tools[agent_type]
    elif agent_type:
        result["specialized_tools"] = []
    else:
        # Return all specialized tools
        result["all_specialized_tools"] = specialized_tools

    return result


# ==================== CONNECTOR MANAGEMENT ====================

@router.get("/connectors")
async def list_connectors(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """List all configured connectors"""
    query = select(ServiceCredential).where(
        ServiceCredential.client_id == current_user.client_id,
        ServiceCredential.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    connectors = result.scalars().all()

    return {
        "connectors": [
            {
                "id": c.id,
                "name": c.name,
                "connector_type": c.provider,
                "is_active": c.is_active,
                "is_verified": c.is_verified,
                "last_verified_at": c.last_verified_at,
                "created_at": c.created_at
            }
            for c in connectors
        ]
    }


@router.post("/connectors")
async def create_connector(
    connector_data: ConnectorConfigCreate,
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Create a new connector configuration"""
    # Build credentials based on connector type
    credentials = {}

    if connector_data.connector_type == ConnectorType.CUSTOM_API:
        credentials = {
            "base_url": connector_data.base_url,
            "auth_type": connector_data.auth_type,
            "auth_credentials": connector_data.auth_credentials,
            "endpoint_mappings": connector_data.endpoint_mappings or {},
            "field_mappings": connector_data.field_mappings or {}
        }
    elif connector_data.connector_type == ConnectorType.CUSTOM_DATABASE:
        credentials = {
            "db_type": connector_data.db_type,
            "host": connector_data.db_host,
            "port": connector_data.db_port,
            "database": connector_data.db_name,
            "username": connector_data.db_user,
            "password": connector_data.db_password,
            "query_mappings": connector_data.query_mappings or {}
        }
    elif connector_data.connector_type in [ConnectorType.SHOPIFY, ConnectorType.WOOCOMMERCE]:
        credentials = {
            "store_url": connector_data.store_url,
            "api_key": connector_data.api_key,
            "api_secret": connector_data.api_secret
        }

    connector = ServiceCredential(
        client_id=current_user.client_id,
        service_type=ServiceType.CHATBOT,
        provider=connector_data.connector_type.value,
        credential_type="connector",
        name=connector_data.name,
        credentials=credentials,
        is_active=connector_data.is_active
    )

    db.add(connector)
    await db.commit()
    await db.refresh(connector)

    return {
        "id": connector.id,
        "name": connector.name,
        "connector_type": connector.provider,
        "is_active": connector.is_active,
        "message": "Connector created successfully. Please test the connection."
    }


@router.post("/connectors/{connector_id}/test")
async def test_connector(
    connector_id: int,
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Test a connector connection"""
    query = select(ServiceCredential).where(
        ServiceCredential.id == connector_id,
        ServiceCredential.client_id == current_user.client_id
    )
    result = await db.execute(query)
    connector = result.scalar_one_or_none()

    if not connector:
        raise HTTPException(status_code=404, detail="Connector not found")

    # Call chatbot service to test connection
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.post(
                f"{settings.CHATBOT_SERVICE_URL}/api/connectors/test",
                json={
                    "connector_type": connector.provider,
                    "credentials": connector.credentials
                },
                headers={"X-Client-ID": str(current_user.client_id)}
            )

            if response.status_code == 200:
                result_data = response.json()

                # Update verification status
                connector.is_verified = result_data.get("success", False)
                connector.last_verified_at = datetime.utcnow()
                await db.commit()

                return result_data
            else:
                return {
                    "success": False,
                    "error": "Failed to test connection",
                    "details": response.text
                }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }


@router.delete("/connectors/{connector_id}")
async def delete_connector(
    connector_id: int,
    current_user: User = Depends(require_permissions("chatbot:delete")),
    db: AsyncSession = Depends(get_db)
):
    """Delete a connector"""
    query = select(ServiceCredential).where(
        ServiceCredential.id == connector_id,
        ServiceCredential.client_id == current_user.client_id
    )
    result = await db.execute(query)
    connector = result.scalar_one_or_none()

    if not connector:
        raise HTTPException(status_code=404, detail="Connector not found")

    await db.delete(connector)
    await db.commit()

    return {"message": "Connector deleted successfully"}


# ==================== KNOWLEDGE BASE / RAG ====================

@router.get("/knowledge-base")
async def list_documents(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """List all knowledge base documents"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/knowledge-base/documents",
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Chatbot service unavailable: {str(e)}")


@router.post("/knowledge-base/upload")
async def upload_document(
    file: UploadFile = File(...),
    name: str = Form(...),
    description: str = Form(None),
    document_type: str = Form("general"),
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Upload a document to knowledge base"""
    # Validate file type
    allowed_types = [".pdf", ".docx", ".txt", ".md", ".csv"]
    file_ext = "." + file.filename.split(".")[-1].lower() if "." in file.filename else ""

    if file_ext not in allowed_types:
        raise HTTPException(
            status_code=400,
            detail=f"File type not allowed. Allowed types: {', '.join(allowed_types)}"
        )

    # Forward to chatbot service
    try:
        async with httpx.AsyncClient(timeout=120.0) as client:
            files = {"file": (file.filename, await file.read(), file.content_type)}
            data = {
                "name": name,
                "description": description or "",
                "document_type": document_type
            }

            response = await client.post(
                f"{settings.CHATBOT_SERVICE_URL}/api/knowledge-base/upload",
                files=files,
                data=data,
                headers={"X-Client-ID": str(current_user.client_id)}
            )

            if response.status_code == 200:
                return response.json()
            else:
                raise HTTPException(status_code=response.status_code, detail=response.text)
    except httpx.TimeoutException:
        raise HTTPException(status_code=504, detail="Document processing timed out")
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Failed to upload document: {str(e)}")


@router.delete("/knowledge-base/{document_id}")
async def delete_document(
    document_id: str,
    current_user: User = Depends(require_permissions("chatbot:delete")),
    db: AsyncSession = Depends(get_db)
):
    """Delete a document from knowledge base"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.delete(
                f"{settings.CHATBOT_SERVICE_URL}/api/knowledge-base/documents/{document_id}",
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Failed to delete document: {str(e)}")


# ==================== HUMAN HANDOFF ====================

@router.get("/handoff/config")
async def get_handoff_config(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get handoff configuration"""
    query = select(ServiceConfig).where(
        ServiceConfig.client_id == current_user.client_id,
        ServiceConfig.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    config = result.scalar_one_or_none()

    if not config:
        return {"handoff_config": {}}

    return {"handoff_config": config.settings.get("handoff", {})}


@router.put("/handoff/config")
async def update_handoff_config(
    config_data: HandoffConfigUpdate,
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Update handoff configuration"""
    query = select(ServiceConfig).where(
        ServiceConfig.client_id == current_user.client_id,
        ServiceConfig.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    config = result.scalar_one_or_none()

    if not config:
        raise HTTPException(status_code=404, detail="Agent configuration not found")

    handoff_settings = {
        "enabled": config_data.enabled,
        "handoff_keywords": config_data.handoff_keywords,
        "negative_sentiment_threshold": config_data.negative_sentiment_threshold,
        "max_ai_failures": config_data.max_ai_failures,
        "high_value_threshold": config_data.high_value_threshold,
        "business_hours": config_data.business_hours,
        "handoff_message": config_data.handoff_message,
        "no_agent_message": config_data.no_agent_message
    }

    config.settings["handoff"] = handoff_settings
    config.updated_at = datetime.utcnow()
    await db.commit()

    # Notify chatbot service
    await _notify_chatbot_service(
        current_user.client_id,
        "handoff_config_updated",
        handoff_settings
    )

    return {"message": "Handoff configuration updated", "handoff_config": handoff_settings}


@router.get("/handoff/agents")
async def list_handoff_agents(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """List human agents for handoff"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/handoff/agents",
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


@router.post("/handoff/agents")
async def create_handoff_agent(
    agent_data: HandoffAgentCreate,
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Create a human agent for handoff"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.post(
                f"{settings.CHATBOT_SERVICE_URL}/api/handoff/agents",
                json=agent_data.dict(),
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


@router.get("/handoff/queue")
async def get_handoff_queue(
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get current handoff queue"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/handoff/queue",
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


# ==================== ANALYTICS ====================

@router.get("/analytics/dashboard")
async def get_analytics_dashboard(
    period: str = "week",
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get chatbot analytics dashboard"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/analytics/dashboard",
                params={"period": period},
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


@router.get("/analytics/conversations")
async def get_conversation_analytics(
    period: str = "week",
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get conversation analytics and trends"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/analytics/conversations",
                params={"period": period},
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


@router.get("/analytics/tools")
async def get_tool_analytics(
    period: str = "week",
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get tool usage analytics"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/analytics/tools",
                params={"period": period},
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


# ==================== CONVERSATIONS ====================

@router.get("/conversations")
async def list_conversations(
    page: int = 1,
    limit: int = 20,
    status: Optional[str] = None,
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """List all conversations"""
    try:
        params = {"page": page, "limit": limit}
        if status:
            params["status"] = status

        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/conversations",
                params=params,
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


@router.get("/conversations/{conversation_id}")
async def get_conversation(
    conversation_id: str,
    current_user: User = Depends(require_permissions("chatbot:read")),
    db: AsyncSession = Depends(get_db)
):
    """Get conversation details with messages"""
    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.get(
                f"{settings.CHATBOT_SERVICE_URL}/api/conversations/{conversation_id}",
                headers={"X-Client-ID": str(current_user.client_id)}
            )
            return response.json()
    except Exception as e:
        raise HTTPException(status_code=503, detail=f"Service unavailable: {str(e)}")


# ==================== WEBHOOKS ====================

@router.post("/webhooks/configure")
async def configure_webhook(
    webhook_url: str,
    events: List[str],
    current_user: User = Depends(require_permissions("chatbot:write")),
    db: AsyncSession = Depends(get_db)
):
    """Configure webhook for chatbot events"""
    query = select(ServiceConfig).where(
        ServiceConfig.client_id == current_user.client_id,
        ServiceConfig.service_type == ServiceType.CHATBOT
    )
    result = await db.execute(query)
    config = result.scalar_one_or_none()

    if not config:
        raise HTTPException(status_code=404, detail="Agent configuration not found")

    import secrets
    webhook_secret = secrets.token_urlsafe(32)

    config.webhook_url = webhook_url
    config.webhook_secret = webhook_secret
    config.webhook_events = events
    config.updated_at = datetime.utcnow()
    await db.commit()

    return {
        "message": "Webhook configured successfully",
        "webhook_url": webhook_url,
        "webhook_secret": webhook_secret,
        "events": events
    }


# ==================== HELPER FUNCTIONS ====================

def _get_default_system_prompt(agent_type: AgentType) -> str:
    """Get default system prompt based on agent type"""
    prompts = {
        AgentType.ECOMMERCE: "You are a helpful e-commerce assistant. Help customers with product inquiries, orders, and support.",
        AgentType.RESTAURANT: "You are a restaurant assistant. Help customers with reservations, menu inquiries, and orders.",
        AgentType.HEALTHCARE: "You are a healthcare assistant. Help patients with appointments, general inquiries, and information.",
        AgentType.REAL_ESTATE: "You are a real estate assistant. Help clients find properties, schedule viewings, and answer property questions.",
        AgentType.CRM: "You are a CRM assistant. Help sales teams with contacts, deals, and pipeline management.",
        AgentType.ERP: "You are an ERP assistant. Help with purchase orders, inventory, and supplier management.",
        AgentType.MANUFACTURING: "You are a manufacturing assistant. Help with production orders, machine status, and quality reports.",
    }
    return prompts.get(agent_type, "You are a helpful AI assistant.")


def _get_default_tools(agent_type: AgentType) -> List[str]:
    """Get default enabled tools based on agent type"""
    core_tools = ["get_sales", "get_orders", "get_products", "get_customers"]

    specialized = {
        AgentType.RESTAURANT: ["get_reservations", "create_reservation", "get_tables", "get_menu"],
        AgentType.HEALTHCARE: ["get_patients", "get_appointments", "create_appointment", "get_doctor_schedule"],
        AgentType.REAL_ESTATE: ["search_properties", "get_property_details", "schedule_property_tour", "calculate_emi"],
        AgentType.CRM: ["get_contacts", "get_deals", "get_pipeline_summary", "create_activity"],
        AgentType.ERP: ["get_purchase_orders", "get_suppliers", "get_accounts_payable"],
        AgentType.MANUFACTURING: ["get_production_orders", "get_machine_status", "get_quality_reports"],
    }

    return core_tools + specialized.get(agent_type, [])


async def _notify_chatbot_service(client_id: int, event: str, data: dict):
    """Notify chatbot service about configuration changes"""
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            await client.post(
                f"{settings.CHATBOT_SERVICE_URL}/api/internal/config-update",
                json={
                    "client_id": client_id,
                    "event": event,
                    "data": data
                }
            )
    except Exception as e:
        logger.warning(f"Failed to notify chatbot service: {str(e)}")
