# handlers/command_handlers.py

from telegram import Update
from telegram.ext import ContextTypes
from services import supabase_service, org_chart_service
from handlers.state import search_state
import logging

logger = logging.getLogger(__name__)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    chat_id = update.effective_chat.id
    logger.info(f"/start - Chat ID: {chat_id}")

    message = (
        "📢 *산업부·기재부·전력그룹사 인사 발령 알림 봇*\n\n"
        "아래 명령어를 통해 검색 및 알림 수신을 설정할 수 있습니다.\n"
        "(메뉴 기능을 활용하거나 직접 입력하여 사용 가능합니다.)\n\n"
        "🔍 *직원 검색 기능*\n"
        "1️⃣ `/motie_search` - 산업부 직원 검색\n"
        "2️⃣ `/moef_search` - 기재부 직원 검색\n\n"
        "📌 *주요 간부 명단 조회*\n"
        "3️⃣ `/motie_map` - 산업부 주요 간부 명단 (팀장 이상)\n"
        "4️⃣ `/moef_map` - 기재부 주요 간부 명단 (팀장 이상)\n\n"
        "🔔 *인사발령 알림 설정*\n"
        "📢 *산업부*\n"
        "5️⃣ `/motie_subscribe` - 산업부 인사발령 알림 켜기\n"
        "6️⃣ `/motie_unsubscribe` - 산업부 인사발령 알림 끄기\n\n"
        "📢 *기재부*\n"
        "7️⃣ `/moef_subscribe` - 기재부 인사발령 알림 켜기\n"
        "8️⃣ `/moef_unsubscribe` - 기재부 인사발령 알림 끄기\n\n"
        "📢 *전력그룹사*\n"
        "9️⃣ `/kepco_subscribe` - 전력그룹사 인사발령 알림 켜기\n"
        "🔟 `/kepco_unsubscribe` - 전력그룹사 인사발령 알림 끄기\n\n"
        "ℹ️ *인사발령 정보는 공시된 정부 홈페이지 및 알리오에서 수집됩니다.*\n"
        "(언론 등 외부 출처 인사발령 정보는 포함되지 않습니다.)\n\n"
        "ℹ️ *알림은 미수신이 기본 값이므로, 수신을 원하실 경우 반드시 알림 켜기를 실행해주세요.*"
    )

    await update.message.reply_text(message, parse_mode="Markdown")

async def motie_map(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await org_chart_service.send_org_chart(context.bot, update.effective_chat.id, "motie")

async def moef_map(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await org_chart_service.send_org_chart(context.bot, update.effective_chat.id, "moef")

# 구독 관련 함수들
async def handle_subscribe(update: Update, context: ContextTypes.DEFAULT_TYPE, table: str):
    chat_id = update.effective_chat.id
    first_name = update.effective_chat.first_name
    try:
        supabase_service.upsert_subscription(table, chat_id, first_name)
        await update.message.reply_text("✅ 인사발령 알림을 구독하셨습니다!")
    except Exception as e:
        await update.message.reply_text("❌ 구독 중 오류 발생!")
        logger.error(f"구독 오류: {e}")

async def handle_unsubscribe(update: Update, context: ContextTypes.DEFAULT_TYPE, table: str):
    chat_id = update.effective_chat.id
    try:
        supabase_service.delete_subscription(table, chat_id)
        await update.message.reply_text("🛑 구독이 취소되었습니다.")
    except Exception as e:
        await update.message.reply_text("❌ 구독 취소 중 오류 발생!")
        logger.error(f"구독 취소 오류: {e}")

# 구독 라우터
async def motie_subscribe(update, context): await handle_subscribe(update, context, "motie_subscribers")
async def motie_unsubscribe(update, context): await handle_unsubscribe(update, context, "motie_subscribers")
async def moef_subscribe(update, context): await handle_subscribe(update, context, "moef_subscribers")
async def moef_unsubscribe(update, context): await handle_unsubscribe(update, context, "moef_subscribers")
async def kepco_subscribe(update, context): await handle_subscribe(update, context, "kepco_subscribers")
async def kepco_unsubscribe(update, context): await handle_unsubscribe(update, context, "kepco_subscribers")

# 검색 명령어
async def motie_search(update, context):
    chat_id = update.effective_chat.id
    search_state[chat_id] = "motie"
    await update.message.reply_text("🔎 산업부에서 검색할 이름을 입력하세요.")

async def moef_search(update, context):
    chat_id = update.effective_chat.id
    search_state[chat_id] = "moef"
    await update.message.reply_text("🔎 기재부에서 검색할 이름을 입력하세요.")

from services import motie_service

# 최신 인사 공지 체크
async def motie_check(update: Update, context: ContextTypes.DEFAULT_TYPE):
    result = motie_service.check_latest_notice()
    if result:
        msg = f"🆕 인사 공지 발견!\n\n제목: {result['title']}\n날짜: {result['date']}\n링크: {result['url']}"
    else:
        msg = "📭 새로운 인사 공지는 없습니다."
    await update.message.reply_text(msg)

# 조직도 전체 크롤링 및 업데이트
async def motie_update(update: Update, context: ContextTypes.DEFAULT_TYPE):
    try:
        changes = motie_service.update_org_chart()  # 변화점 반환
        if not changes:
            msg = "✅ 조직도에는 변화가 없습니다."
        else:
            msg = "📊 다음과 같은 변화가 발견되었습니다:\n\n"
            for line in changes:
                msg += f"- {line}\n"
        await update.message.reply_text(msg)
    except Exception as e:
        await update.message.reply_text("❌ 조직도 업데이트 중 오류 발생!")
        logging.error(f"motie_update 오류: {e}")