#!/usr/bin/env python3
"""scope_violation_alert.py — Scope violation 별도 채널 helper (task-2370).

auto_merge.py 또는 task-scope-guard 흐름에서 import하여 send_scope_violation()을 호출.
환경변수:
  ANU_CONFIRM_BOT_TOKEN, SCOPE_VIOLATION_CHAT_ID (미설정 시 ANU_CONFIRM_CHAT_ID 사용)
"""
from __future__ import annotations

import json
import logging
import os
import urllib.parse
import urllib.request

logger = logging.getLogger("scope_violation_alert")

BOT_TOKEN = os.environ.get("ANU_CONFIRM_BOT_TOKEN", "")
PRIMARY_CHAT = os.environ.get("ANU_CONFIRM_CHAT_ID", "")
SCOPE_CHAT = os.environ.get("SCOPE_VIOLATION_CHAT_ID", "") or PRIMARY_CHAT


def format_violation_message(task_id: str, violations: list[str], context: dict | None = None) -> str:
    """⚠️ SCOPE VIOLATION prefix + bold HTML."""
    ctx = context or {}
    lines = [
        f"<b>⚠️ SCOPE VIOLATION — {task_id}</b>",
        "",
        f"위반 파일/명령 ({len(violations)}건):",
    ]
    for v in violations[:20]:
        lines.append(f"  • <code>{v}</code>")
    if len(violations) > 20:
        lines.append(f"  ... (총 {len(violations)}건)")
    if ctx:
        lines.append("")
        lines.append("컨텍스트:")
        for k, v in ctx.items():
            lines.append(f"  - {k}: {v}")
    return "\n".join(lines)


def send_scope_violation(task_id: str, violations: list[str], context: dict | None = None, dry_run: bool = False) -> dict:
    """Scope violation 알림 발송. 별도 chat_id 우선."""
    text = format_violation_message(task_id, violations, context)
    chat_id = SCOPE_CHAT
    if not chat_id or not BOT_TOKEN or dry_run:
        logger.info(f"scope_violation dry-run: chat={chat_id or 'unset'}, token={'set' if BOT_TOKEN else 'unset'}")
        return {"ok": False, "dry_run": True, "text": text, "chat_id": chat_id}
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = urllib.parse.urlencode({
        "chat_id": chat_id,
        "text": text,
        "parse_mode": "HTML",
    }).encode("utf-8")
    try:
        with urllib.request.urlopen(url, data=payload, timeout=10) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except Exception as exc:
        logger.error(f"scope violation 발송 실패: {exc}")
        return {"ok": False, "error": str(exc), "text": text}


if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print("Usage: scope_violation_alert.py <task_id> [violation1] [violation2] ...")
        sys.exit(2)
    task = sys.argv[1]
    vs = sys.argv[2:] or ["(no violations specified)"]
    result = send_scope_violation(task, vs, dry_run=True)
    print(json.dumps(result, ensure_ascii=False, indent=2))
