import os
from pathlib import Path
from dotenv import load_dotenv
from html import escape as _escape

# .env 로드 (systemd 단독 실행 대비)
BASE_DIR = Path(__file__).resolve().parents[2]  # /var/www/html/govbot
load_dotenv(BASE_DIR / ".env")

from app.crawlers.motie import crawl_motie
from app.crawlers.moef import crawl_moef
from app.services.notify_service import broadcast_telegram
from app.services.supabase_service import (
    get_active_chat_ids,
    has_motie_id, insert_motie_id,
    has_moef_id, insert_moef_id,
)

def _msg(source_kor: str, title: str, url: str,
         posted_at: str | None = None, tag: str | None = None) -> str:
    """통일 메시지 포맷 (HTML)"""
    title_s = _escape(title or "")
    body = [f"🏛️ {source_kor} 인사발령", ""]
    if tag:
        body.append(f"분류: {_escape(tag)}")
    if posted_at:
        body.append(f"게시일: {posted_at}")
    body.append(f"제목: {title_s}")
    body.append(f'<a href="{url}">🔗 인사발령 상세 보기</a>')
    return "\n".join(body)

def run_once():
    ua = os.getenv("USER_AGENT", "govbot/1.0")
    chat_ids = get_active_chat_ids()

    msgs: list[str] = []

    # --- MOTIE ---
    try:
        for item in crawl_motie(ua, page=1):
            aid = item["articleId"]  # 문자열
            if has_motie_id(aid):
                continue
            insert_motie_id(
                aid,
                title=item.get("title") or "산업부 인사발령",
                posted_at=item.get("posted_at"),
            )
            msgs.append(_msg(
                source_kor="산업통상자원부",
                title=item.get("title", ""),
                url=item.get("url", ""),
                posted_at=item.get("posted_at"),
                tag=None,
            ))
    except Exception as e:
        msgs.append(f"[Crawl] MOTIE 실패: {e}")

    # --- MOEF (tag/posted_at 포함) ---
    try:
        for item in crawl_moef(ua):
            mid = item["item_id"]  # bbsId-postId
            if has_moef_id(mid):
                continue
            insert_moef_id(
                mid,
                bbs_id=item["bbsId"],
                post_id=item["postId"],
                title=item.get("title") or "기재부 인사발령",
                tag=item.get("tag"),
                posted_at=item.get("posted_at"),
            )
            msgs.append(_msg(
                source_kor="기획재정부",
                title=(f"[{item.get('tag')}] {item.get('title','')}" if item.get("tag") else item.get("title","")),
                url=item.get("url", ""),
                posted_at=item.get("posted_at"),
                tag=item.get("tag"),
            ))
    except Exception as e:
        msgs.append(f"[Crawl] MOEF 실패: {e}")

    # --- 브로드캐스트: 신규나 오류가 있을 때만 발송 ---
    if chat_ids and msgs:
        for m in msgs:
            broadcast_telegram(m, chat_ids, parse_mode="HTML")

if __name__ == "__main__":
    run_once()
