import asyncio
import os


async def command_handler_flow(client):
    """命令行交互。"""
    client.logger.info("\n命令帮助:")
    client.logger.info("  reply <内容>     - 回复最后一条消息")
    client.logger.info("  text <id> <平台> <内容>  - 发送文本消息")
    client.logger.info("  img <id> <平台> <路径>   - 发送图片")
    client.logger.info("  setid <id>       - 设置回复ID")
    client.logger.info("  agent on/off     - 开启/关闭 Agent")
    client.logger.info("  exit/quit        - 退出\n")

    while client.running:
        try:
            loop = asyncio.get_running_loop()
            user_input = await loop.run_in_executor(None, input, "")

            parts = user_input.strip().split(maxsplit=1)
            if not parts:
                continue

            cmd = parts[0].lower()

            if cmd in ["exit", "quit", "q"]:
                client.logger.info(f"[{client.get_time()}] 正在关闭...")
                client.running = False
                if client.websocket:
                    await client.websocket.close()
                break

            if cmd == "setid" and len(parts) > 1:
                client.reply_id = parts[1]
                client.logger.info(f"[{client.get_time()}] 回复ID已设置为: {client.reply_id}")
                continue

            if cmd == "agent" and len(parts) > 1:
                if parts[1].lower() == "on":
                    client.enable_agent = True
                    client.logger.info(f"[{client.get_time()}] Agent 已开启")
                elif parts[1].lower() == "off":
                    client.enable_agent = False
                    client.logger.info(f"[{client.get_time()}] Agent 已关闭")
                continue

            if cmd == "reply" and len(parts) > 1:
                if client.last_msg:
                    await client.send_reply(client.last_msg, parts[1])
                else:
                    client.logger.info(f"[{client.get_time()}] 错误: 还没有收到任何消息")
                continue

            if cmd == "text" and len(parts) > 1:
                args = parts[1].split(maxsplit=2)
                if len(args) >= 3:
                    await client.send_text(args[0], args[1], args[2])
                else:
                    client.logger.info(f"[{client.get_time()}] 格式: text <cy_id> <acc_type> <内容>")
                continue

            if cmd == "img" and len(parts) > 1:
                args = parts[1].split(maxsplit=2)
                if len(args) >= 3:
                    await client.send_image(args[0], args[1], args[2])
                else:
                    client.logger.info(f"[{client.get_time()}] 格式: img <cy_id> <acc_type> <图片路径>")
                continue

            client.logger.info(f"[{client.get_time()}] 未知命令: {cmd}")

        except Exception as e:
            client.logger.info(f"[{client.get_time()}] 命令错误: {e}")


async def run_client_flow(client):
    """运行客户端。"""
    tasks = [client.connect(), client.command_handler()]

    try:
        from mail.email_receiver import email_receiver
        if email_receiver.username:
            client.logger.info(f"[{client.get_time()}] 邮件接收已启动，监控: {email_receiver.username}")
            tasks.append(email_receiver.start())
        else:
            client.logger.info(f"[{client.get_time()}] 未配置邮件账号，跳过邮件接收")
    except Exception as e:
        client.logger.info(f"[{client.get_time()}] 邮件接收模块加载失败: {e}")

    try:
        from utils.daily_summary import scheduler as daily_scheduler
        tasks.append(daily_scheduler())
        client.logger.info(f"[{client.get_time()}] 每日日报定时任务已启动")
    except Exception as e:
        client.logger.info(f"[{client.get_time()}] 日报模块加载失败: {e}")

    try:
        from utils.health_check import health_check_loop

        def _qingjian_ok():
            return client.websocket is not None and not getattr(client.websocket, "closed", True)

        tasks.append(health_check_loop(_qingjian_ok))
        client.logger.info(f"[{client.get_time()}] 健康检查已启动")
    except Exception as e:
        client.logger.info(f"[{client.get_time()}] 健康检查模块加载失败: {e}")

    try:
        from utils.wechat_chat_log import morning_startup_scheduler
        tasks.append(morning_startup_scheduler())
        client.logger.info(f"[{client.get_time()}] 早8点企微启动消息已启动")
    except Exception as e:
        client.logger.info(f"[{client.get_time()}] 企微启动消息模块加载失败: {e}")

    if os.getenv("UNREPLIED_FOLLOWUP_ENABLED", "true").lower() in ("1", "true", "yes"):
        tasks.append(client._unreplied_followup_loop())
        client.logger.info(f"[{client.get_time()}] 未回复会话补偿任务已启动")

    await asyncio.gather(*tasks)
