import os, html
from flask import Blueprint, request, jsonify
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Application, CommandHandler, ContextTypes
from ..supabase_client import get_client

bot_bp = Blueprint("bot", __name__)

BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
WEBHOOK_URL = os.getenv("TELEGRAM_WEBHOOK_URL")

application = Application.builder().token(BOT_TOKEN).build()

async def start(update: Update, _: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "안녕하세요! 대정부/전력그룹사 검색·알림 봇입니다.\n"
        "/search, /subscribe, /status, /help 를 사용해보세요."
    )

async def help_cmd(update: Update, _: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "/search <키워드> [--org=MOTIE|MOEF|KEPCO] [--type=emp|exec]\n"
        "/subscribe [on|off] [--org=MOTIE|MOEF|KEPCO|ALL]\n"
        "/status"
    )

def parse_args(text: str) -> dict:
    parts = text.split()[1:] if text else []
    args = {"org": None, "type": None, "toggle": None}
    for p in parts:
        if p.startswith("--org="):
            args["org"] = p.split("=",1)[1].upper()
        elif p.startswith("--type="):
            args["type"] = p.split("=",1)[1].lower()
        elif p in ("on","off"):
            args["toggle"] = p
    return args

async def search_cmd(update: Update, _: ContextTypes.DEFAULT_TYPE):
    supa = get_client()
    text = update.message.text or ""
    args = parse_args(text)
    q = None
    toks = text.split(maxsplit=1)
    if len(toks) >= 2:
        # 키워드 분리 (옵션 제외)
        q = toks[1]
        for k in ["--org=","--type="," on"," off"]:
            q = q.replace(k,"")
        q = q.strip()
    if not q:
        await update.message.reply_text("예: /search 홍길동 --org=MOTIE")
        return
    org = args["org"] or ""
    typ = args["type"] or "emp"

    def like_any(table, fields):
        for f in fields:
            data = supa.table(table).select("*").ilike(f, f"%{q}%").limit(10).execute().data
            if data:
                return data
        return []

    lines = []
    if typ == "emp":
        if org == "MOTIE":
            rows = like_any("motie_org", ["name","department","position","task"])
        elif org == "MOEF":
            rows = like_any("moef_org", ["name","department","position","task"])
        elif org == "KEPCO":
            rows = like_any("kepco_org", ["name","department","position","task"])
        else:
            rows = like_any("motie_org", ["name","department"]) + like_any("moef_org", ["name","department"])
    else:
        rows = []
        if org in ("","MOTIE","ALL"):
            rows += like_any("motie_vip", ["name","department","position","task"])
        if org in ("","MOEF","ALL"):
            rows += like_any("moef_vip", ["name","department","position","task"])
        if org in ("","KEPCO","ALL"):
            r = like_any("kepco_org", ["name","position","department"])
            keywords = ["사장","부사장","사외이사","상임감사","전무","상무","본부장","처장","실장"]
            r = [x for x in r if any(k in (x.get("position") or "") for k in keywords)]
            rows += r

    for r in rows[:20]:
        name = r.get("name") or "-"
        pos = r.get("position") or "-"
        dept = r.get("department") or "-"
        phone = r.get("phone") or r.get("contact") or "-"
        lines.append(f"{name} / {pos} / {dept} / {phone}")

    await update.message.reply_text("\n".join(lines)[:4000] or "검색 결과가 없습니다.")

async def subscribe_cmd(update: Update, _: ContextTypes.DEFAULT_TYPE):
    # 단일 명령: on -> insert/upsert, off -> delete
    supa = get_client()
    text = update.message.text or ""
    args = parse_args(text)
    toggle = args["toggle"]
    if toggle not in ("on","off"):
        kb = InlineKeyboardMarkup(
            [[InlineKeyboardButton("ON", callback_data="sub:ON"),
              InlineKeyboardButton("OFF", callback_data="sub:OFF")]]
        )
        await update.message.reply_text("구독 설정을 선택하세요:", reply_markup=kb)
        return
    uid = update.effective_user.id
    name = update.effective_user.first_name
    if toggle == "on":
        supa.table("subscribers").upsert({"chat_id": uid, "first_name": name}).execute()
        await update.message.reply_text("알림 구독이 활성화되었습니다.")
    else:
        supa.table("subscribers").delete().eq("chat_id", uid).execute()
        await update.message.reply_text("알림 구독이 해제되었습니다.")

async def status_cmd(update: Update, _: ContextTypes.DEFAULT_TYPE):
    supa = get_client()
    uid = update.effective_user.id
    row = supa.table("subscribers").select("*").eq("chat_id", uid).limit(1).execute().data
    msg = "구독 상태: ON" if row else "구독 상태: OFF"
    await update.message.reply_text(msg)

@bot_bp.route("/webhook", methods=["POST"])
def webhook():
    """Telegram webhook 엔드포인트"""
    if request.method == "POST":
        update = Update.de_json(request.get_json(force=True), application.bot)
        application.update_queue.put_nowait(update)
        return jsonify({"ok": True})
    return jsonify({"ok": False}), 405

# 핸들러 등록
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_cmd))
application.add_handler(CommandHandler("search", search_cmd))
application.add_handler(CommandHandler("subscribe", subscribe_cmd))
application.add_handler(CommandHandler("status", status_cmd))
