import logging
import re
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

# 启用日志，方便调试
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)

# ================= 配置区域 =================
BOT_TOKEN = "8304415303:AAEJao1DfgYZ1H9apXmJ4C7iM5cUZl3QZzo"
MY_PERSONAL_ID = 1003097427  # 这里填你自己的 Telegram 纯数字账号 ID
# ============================================

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """/start 命令，用于获取当前群组的 ID 或测试机器人"""
    chat = update.effective_chat
    if chat.type in ['group', 'supergroup']:
        await update.message.reply_text(f"机器人已在群组中激活！\n当前群组 ID: `{chat.id}`", parse_mode="Markdown")
    else:
        await update.message.reply_text(f"你好！你的个人 Telegram ID 是: `{chat.id}`\n请将此 ID 填入代码的 MY_PERSONAL_ID 中。", parse_mode="Markdown")

async def forward_to_admin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """核心逻辑 1：把群里顾客的消息，转发给你（管理员）"""
    # 确保这条消息不是来自你本人，且来自群组（避免死循环和重复投递）
    if update.effective_user.id == MY_PERSONAL_ID:
        return

    chat = update.effective_chat
    user = update.effective_user
    message = update.message

    # 只处理群组或超级群组里的消息
    if chat.type in ['group', 'supergroup']:
        group_title = chat.title
        group_id = chat.id
        username = f"@{user.username}" if user.username else "无用户名"
        
        # 构造发送给你的文本头，关键在于 [GID: {group_id}] 这个标签，后续靠它识别回传路径
        header = f"来自群【{group_title}】\n用户: {user.full_name} ({username})\n[GID: {group_id}]\n"
        
        if message.text:
            # 转发纯文本
            await context.bot.send_message(
                chat_id=MY_PERSONAL_ID,
                text=f"{header}内容：\n{message.text}"
            )
        else:
            # 如果是图片、文件等，先发带有标签的文本，再复制媒体内容
            # 注意：本基础脚本主要演示文本路由，如需完美转发图片/媒体，可根据需要扩展
            await context.bot.send_message(
                chat_id=MY_PERSONAL_ID,
                text=f"{header}发送了媒体文件，请在群内查看或通过 ID 回复。"
            )

async def reply_to_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """核心逻辑 2：你在私聊中回复机器人，机器人帮你把消息发回对应的群"""
    # 确保只有你（管理员）在私聊中触发这个逻辑
    if update.effective_user.id != MY_PERSONAL_ID or update.effective_chat.type != 'private':
        return

    message = update.message

    # 必须是“回复（Reply）”了某条消息
    if not message.reply_to_message:
        await message.reply_text("提示：请直接【回复】机器人发给你的那条顾客消息来发表回复。")
        return

    # 从你回复的那条历史消息中，用正则表达式提取出 [GID: -xxxxxx] 里的群 ID
    parent_text = message.reply_to_message.text or message.reply_to_message.caption
    if not parent_text:
        await message.reply_text("错误：无法读取上文的群组标签。")
        return

    match = re.search(r'\[GID:\s*(-?\d+)\]', parent_text)
    
    if match:
        target_group_id = int(match.group(1))
        try:
            # 以机器人的名义，把你的回复内容发送到那个群里
            await context.bot.send_message(chat_id=target_group_id, text=message.text)
            await message.reply_text("✅ 消息已成功送达群组！")
        except Exception as e:
            await message.reply_text(f"❌ 发送失败，原因：{e}\n请检查机器人是否还在该群内，且拥有发言权限。")
    else:
        await message.reply_text("❌ 找不到有效的群组 ID 标签，请确保你是对着机器人转发的消息进行回复。")

def main():
    """启动机器人"""
    # 初始化 Application
    application = Application.builder().token(BOT_TOKEN).build()

    # 注册命令处理器
    application.add_handler(CommandHandler("start", start))

    # 注册消息处理器
    # 1. 处理私聊中你的回复动作（优先判断）
    application.add_handler(MessageHandler(filters.ChatType.PRIVATE & filters.TEXT & ~filters.COMMAND, reply_to_group))
    # 2. 处理群组里顾客发的消息（过滤掉命令）
    application.add_handler(MessageHandler((filters.ChatType.GROUPS) & ~filters.COMMAND, forward_to_admin))

    # 启动轮询
    print("机器人正在运行中...")
    application.run_polling()

if __name__ == '__main__':
    main()