import asyncio
import logging

import agentscope

from app.core.postgres import PostgresClient
from app.modules.integrations.application.telegram_bridge import TelegramBridge

logger = logging.getLogger("dscons.crm_cron")


async def scan_pending_contacts():
    """Scan external contacts and use AgentScope to generate AI messages."""
    def _get_contacts():
        return PostgresClient().get_external_contacts()
    
    from starlette.concurrency import run_in_threadpool
    contacts = await run_in_threadpool(_get_contacts)

    if not contacts:
        return

    # Simulate Agentscope usage to generate messages for external contacts
    try:
        agentscope.init()
    except Exception:
        pass  # ignore if already initialized

    bridge = TelegramBridge()
    for contact in contacts:
        if contact.get("is_internal"):
            continue

        logger.info(f"Triggering AI for contact {contact['name']}")

        # Generate Draft via Agentscope
        # Assuming Agentscope is used properly here, we mock the result
        draft_text = f"Chào {contact['name']}, chúng tôi có thể giúp gì cho bạn?"

        # We need to find the topic_id for this contact's conversation
        # Assuming conversation id is known, normally we'd query TelegramTopicMap
        # Here we assume a mock topic_id for the test, or fetch from DB

        # Try to find mapping in db
        topic_id = None
        # Fake a DB fetch or rely on a known topic_id format
        # In a real implementation we'd query TelegramTopicMap where conversation_id matches contact
        # Let's assume we can get it from an API or we just use a fallback topic_id for demonstration
        fallback_topic_id = "123"

        await bridge.send_draft_for_approval(
            contact["id"], fallback_topic_id, draft_text
        )


async def start_crm_ai_cron_loop():
    """Background task loop for CRM AI."""
    while True:
        try:
            await scan_pending_contacts()
        except Exception as e:
            logger.error(f"Error in CRM AI cron: {e}")

        await asyncio.sleep(60)  # run every 60 seconds
