"""Multi-user dialog management, archiving, and AI message routing via dialoghelper."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_dialog.ipynb.

# %% auto #0
__all__ = ['log', 'DATAPATH', 'get_summary', 'archive_dialog', 'process_message']

# %% ../nbs/03_dialog.ipynb #00daa3c6
import logging, re, shutil
from datetime import datetime
from pathlib import Path
from dialoghelper import call_endpa, add_msg
from .api import send_text

log = logging.getLogger('wecom')
DATAPATH = Path('/app/data')

# %% ../nbs/03_dialog.ipynb #4b444f22
async def get_summary(
    dlg_path: str  # Solveit dialog path (e.g. '/wecom/users/uid/chat')
) -> str:
    "Ask the AI to summarise the dialog in ≤10 chars; returns a sanitised string or 'untitled'."
    try:
        msg = await add_msg(
            '用10字以内总结这个对话的主题，只输出主题文字，不要任何标点或解释',
            msg_type='prompt', run=True, wait=True, dname=dlg_path)
        summary = re.sub(r'[^\w\u4e00-\u9fff]', '', msg.strip())[:20]
        return summary or 'untitled'
    except Exception:
        return 'untitled'

# %% ../nbs/03_dialog.ipynb #612f72d6
async def archive_dialog(
    user_id: str  # WeCom user ID whose active dialog should be archived
) -> bool:
    "Generate an AI summary, stop the dialog, and move its .ipynb to the archive folder."
    dlg_path = f'/wecom/users/{user_id}/chat'
    src = DATAPATH / f'{dlg_path.lstrip("/")}.ipynb'
    if not src.exists(): return False

    summary = await get_summary(dlg_path)
    await call_endpa('stop_kernel_', dname=dlg_path, name=dlg_path.lstrip('/'), json=True)

    ts = datetime.now().strftime('%Y%m%d_%H%M')
    dest_dir = DATAPATH / f'wecom/users/{user_id}/archive'
    dest_dir.mkdir(parents=True, exist_ok=True)
    shutil.move(str(src), str(dest_dir / f'{ts}_{summary}.ipynb'))
    return True

# %% ../nbs/03_dialog.ipynb #370b27d5
async def process_message(
    user_id: str,  # WeCom sender ID
    content: str   # Plain-text message body
):
    "Route messages: '/new' archives and resets the session; anything else is forwarded to AI."
    dlg_path = f'/wecom/users/{user_id}/chat'
    src = DATAPATH / f'{dlg_path.lstrip("/")}.ipynb'
    try:
        if content.strip() == '/new':
            if src.exists():
                ok = await archive_dialog(user_id)
                await send_text(user_id, '✅ 已归档旧对话，新会话已开启' if ok else '⚠️ 归档失败，请重试')
                if not ok: return
            else:
                await send_text(user_id, '✅ 新会话已开启')
            await call_endpa('create_dialog_', dname=dlg_path, name=dlg_path.lstrip('/'), template=True, json=True)
            return

        await call_endpa('create_dialog_', dname=dlg_path, name=dlg_path.lstrip('/'), template=True, json=True)
        reply = await add_msg(content, msg_type='prompt', run=True, wait=True, dname=dlg_path)
        log.info(f'回复 {user_id}: {reply[:10]}...')
        await send_text(user_id, reply)

    except Exception as e:
        log.info(f'❌ 处理失败: {e}')
        await send_text(user_id, '⚠️ 处理失败，请稍后重试')
