# /var/www/html/govbot/app/workers/org_sync.py
from __future__ import annotations

import os
from pathlib import Path
from dotenv import load_dotenv

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

# ===== latin-1 헤더 이슈 방지: UA/헤더 ASCII 강제 =====
import requests
from urllib.parse import quote

def _ascii_only(s: str, fallback: str = "") -> str:
    if not isinstance(s, str):
        s = str(s)
    try:
        s.encode("ascii")
        return s
    except Exception:
        # ASCII 이외 문자 제거
        return "".join(ch for ch in s if ord(ch) < 128) or fallback

def _sanitize_headers(hdrs):
    """헤더 값에 비 ASCII 문자가 섞이면 urllib3가 latin-1로 인코딩하지 못해 터짐 → 사전 정리"""
    if not hdrs:
        return hdrs
    new = {}
    for k, v in hdrs.items():
        if isinstance(v, bytes):
            # bytes면 그대로 두되, decode 실패 방지 위해 latin-1 범위로만 제한(필요시)
            try:
                v.decode("latin-1")
                new[k] = v
                continue
            except Exception:
                v = v.decode("utf-8", "ignore")
        s = str(v)
        if any(ord(ch) > 127 for ch in s):
            kl = k.lower()
            if kl in ("referer", "referrer", "origin"):
                # URL류는 퍼센트 인코딩으로 ASCII화
                try:
                    s = quote(s, safe=":/?&=#%+@,;")
                except Exception:
                    s = _ascii_only(s)
            else:
                s = _ascii_only(s)
        new[k] = s
    return new

# requests 전역 패치: 전송 직전에 헤더를 안전화
_orig_send = requests.sessions.Session.send
def _patched_send(self, request, **kwargs):
    request.headers = _sanitize_headers(request.headers)
    return _orig_send(self, request, **kwargs)
requests.sessions.Session.send = _patched_send  # noqa

# USER_AGENT 환경 변수도 ASCII로 정제(하위 모듈에서 쓰는 경우 대비)
UA_DEFAULT = "GovBot/1.0 (+https://work.jjickjjicks.com)"
os.environ["USER_AGENT"] = _ascii_only(os.getenv("USER_AGENT", UA_DEFAULT), UA_DEFAULT)

# ===== 실제 동기화 실행 =====
from app.workers.motie_org_sync import run as sync_motie
from app.workers.moef_org_sync import run as sync_moef

def run():
    errors = []
    try:
        sync_motie()
    except Exception as e:
        errors.append(f"MOTIE: {e}")
    try:
        sync_moef()
    except Exception as e:
        errors.append(f"MOEF: {e}")
    if errors:
        # 두 에러를 한 줄로 묶어 raise (웹/봇에 예쁘게 표기)
        raise RuntimeError("; ".join(errors))

if __name__ == "__main__":
    run()
