"""
MyWellnetPTN Discord Gateway SDK for Python
กองสาธารณสุข องค์การบริหารส่วนจังหวัดปัตตานี

คลาสสำหรับเชื่อมต่อระบบแจ้งเตือนสองทาง Discord Multi-Bot Gateway (แบบรวมศูนย์)
รองรับทุกระบบงาน (อนุมัติ, มอบหมายงาน, ตัวชี้วัด, เหตุฉุกเฉิน ฯลฯ)

คุณสมบัติ:
- Zero Dependencies: ใช้เฉพาะโมดูลมาตรฐาน (urllib, hmac, hashlib, json) ไม่ต้องลง pip package เพิ่ม
- มีฟังก์ชันตรวจสอบลายเซ็นดิจิทัล HMAC-SHA256 Webhook ในตัว
- รองรับทั้ง Python 3.8+
"""

import hmac
import hashlib
import json
import urllib.request
import urllib.error
import urllib.parse
from typing import Dict, Any, Optional, List


class MyWellnetGateway:
    def __init__(
        self,
        client_id: str,
        client_secret: str,
        base_url: Optional[str] = None,
        timeout: int = 10
    ):
        self.client_id = client_id.strip()
        self.client_secret = client_secret.strip()
        resolved_base = base_url or os.getenv("DISCORD_GATEWAY_URL") or os.getenv("APP_BASE_URL")
        if not resolved_base:
            raise ValueError("[MyWellnetGateway] กรุณาระบุ base_url หรือกำหนด APP_BASE_URL ในไฟล์ .env")
        self.base_url = str(resolved_base).strip().rstrip("/")
        self.timeout = timeout

    def send(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """ฟังก์ชันหลักสำหรับส่งการแจ้งเตือน (Universal Send)"""
        endpoint = f"{self.base_url}/api/v1/notify"
        data_bytes = json.dumps(params, ensure_ascii=False).encode("utf-8")

        headers = {
            "Content-Type": "application/json",
            "X-Client-ID": self.client_id,
            "X-Client-Secret": self.client_secret
        }

        if "idempotency_key" in params and params["idempotency_key"]:
            headers["X-Idempotency-Key"] = str(params["idempotency_key"])

        req = urllib.request.Request(endpoint, data=data_bytes, headers=headers, method="POST")

        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as response:
                res_body = response.read().decode("utf-8")
                return json.loads(res_body)
        except urllib.error.HTTPError as e:
            err_body = e.read().decode("utf-8")
            try:
                err_json = json.loads(err_body)
                raise RuntimeError(f"[{err_json.get('error', 'GATEWAY_ERROR')}] {err_json.get('message', err_body)}")
            except Exception:
                raise RuntimeError(f"Gateway HTTP Error {e.code}: {err_body}")
        except Exception as e:
            raise RuntimeError(f"ไม่สามารถเชื่อมต่อ MyWellnet Gateway ได้: {str(e)}")

    def send_approval(
        self,
        target_citizen_id: str,
        title: str,
        description: str,
        fields: Optional[List[Dict[str, Any]]] = None,
        doc_url: Optional[str] = None,
        ref_id: str = ""
    ) -> Dict[str, Any]:
        """แม่แบบ 1: ขออนุมัติเอกสาร / คำขอ (Approval Workflow)"""
        actions = [
            {
                "label": "อนุมัติคำขอ",
                "style": "SUCCESS",
                "action_id": f"approve_{ref_id}",
                "emoji": "✅"
            },
            {
                "label": "ไม่อนุมัติ",
                "style": "DANGER",
                "action_id": f"reject_{ref_id}",
                "emoji": "❌",
                "modal": {
                    "title": "ระบุเหตุผลที่ไม่อนุมัติ",
                    "fields": [
                        {
                            "id": "reason",
                            "label": "เหตุผลในการไม่อนุมัติ",
                            "paragraph": True,
                            "required": True,
                            "placeholder": "กรุณาระบุเหตุผล..."
                        }
                    ]
                }
            }
        ]

        if doc_url:
            actions.append({
                "label": "ดูเอกสารแนบ",
                "style": "LINK",
                "url": doc_url,
                "emoji": "📄"
            })

        return self.send({
            "target_citizen_id": target_citizen_id,
            "idempotency_key": f"appr_{ref_id}" if ref_id else None,
            "embed": {
                "title": f"📝 {title}",
                "description": description,
                "color": "#3B82F6",
                "fields": fields or [],
                "footer": {"text": "ระบบขออนุมัติ • MyWellnetPTN Gateway"}
            },
            "actions": actions
        })

    def send_task(
        self,
        target_citizen_id: str,
        task_title: str,
        description: str,
        fields: Optional[List[Dict[str, Any]]] = None,
        task_id: str = ""
    ) -> Dict[str, Any]:
        """แม่แบบ 2: สั่งการและมอบหมายงาน (Task Assignment)"""
        return self.send({
            "target_citizen_id": target_citizen_id,
            "idempotency_key": f"task_{task_id}" if task_id else None,
            "embed": {
                "title": f"📋 {task_title}",
                "description": description,
                "color": "#10B981",
                "fields": fields or [],
                "footer": {"text": "ระบบมอบหมายงาน • MyWellnetPTN"}
            },
            "actions": [
                {
                    "label": "รับทราบและเริ่มปฏิบัติงาน",
                    "style": "SUCCESS",
                    "action_id": f"ack_task_{task_id}",
                    "emoji": "👍"
                },
                {
                    "label": "รายงานความก้าวหน้า",
                    "style": "PRIMARY",
                    "action_id": f"report_task_{task_id}",
                    "emoji": "📝",
                    "modal": {
                        "title": "บันทึกรายงานความก้าวหน้า",
                        "fields": [
                            {"id": "progress_percent", "label": "ความก้าวหน้า (%) เช่น 50", "required": True},
                            {"id": "progress_notes", "label": "รายละเอียดงาน", "paragraph": True, "required": False}
                        ]
                    }
                }
            ]
        })

    def send_alert(
        self,
        target_citizen_id: str,
        alert_title: str,
        message: str,
        fields: Optional[List[Dict[str, Any]]] = None,
        alert_id: str = ""
    ) -> Dict[str, Any]:
        """แม่แบบ 3: แจ้งเตือนเหตุด่วน / เฝ้าระวัง (Alert / Emergency)"""
        return self.send({
            "target_citizen_id": target_citizen_id,
            "idempotency_key": f"alert_{alert_id}" if alert_id else None,
            "embed": {
                "title": f"🚨 {alert_title}",
                "description": message,
                "color": "#EF4444",
                "fields": fields or [],
                "footer": {"text": "ระบบแจ้งเตือนเร่งด่วน • MyWellnetPTN"}
            },
            "actions": [
                {
                    "label": "รับเรื่องทันที",
                    "style": "SUCCESS",
                    "action_id": f"ack_alert_{alert_id}",
                    "emoji": "🏃"
                }
            ]
        })

    def verify_webhook_signature(self, raw_body: str, signature_header: str) -> bool:
        """ตรวจสอบความถูกต้องของ HMAC-SHA256 Webhook Signature"""
        if not raw_body or not signature_header:
            return False
        expected = hmac.new(
            self.client_secret.encode("utf-8"),
            raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body,
            hashlib.sha256
        ).hexdigest()
        return hmac.compare_digest(expected, signature_header)
