# services/telegram_service.py

import os
import requests

TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")  # 기본 채널 ID (옵션)
BASE_ARTICLE_URL = "https://www.motie.go.kr/kor/article/ATCL6e90bb9de/{}/view?"

def send_motie_alert(post: dict, chat_id=None):
    chat_id = chat_id or TELEGRAM_CHAT_ID
    if not chat_id:
        print("[❌] chat_id가 설정되지 않았습니다.")
        return

    title = post.get("title", "").strip()
    article_id = post["articleId"]
    link = BASE_ARTICLE_URL.format(article_id)

    message = (
        "📢 *산업부 인사발령입니다.*\n\n"
        f"📝 {title}\n\n"
        f"👉 [인사발령 상세 보기]({link})"
    )

    try:
        res = requests.post(
            f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage",
            json={
                "chat_id": chat_id,
                "text": message,
                "parse_mode": "Markdown",
                "disable_web_page_preview": True
            }
        )
        res.raise_for_status()
        print(f"[✅] 텔레그램 발송 완료: {article_id}")
    except Exception as e:
        print(f"[❌] 텔레그램 발송 실패: {e}")

from services.motie_service import get_motie_subscribers  # 아래에 추가할 함수

def send_motie_alert_to_all(post: dict):
    subscribers = get_motie_subscribers()
    for sub in subscribers:
        chat_id = sub.get("chat_id")
        if not chat_id:
            print(f"[❌] chat_id 누락됨: {sub}")
            continue
        send_motie_alert(post, chat_id=chat_id)
