"""Feishu + WeChat Work webhook poster (OBS-03).

Both platforms accept simple text webhook posts with slightly different JSON
shapes. Pick the shape based on `alert_provider` (default: feishu).

Feishu:   { "msg_type": "text", "content": {"text": "..."} }
WeChat:   { "msgtype":  "text", "text":    {"content": "..."} }
"""
from __future__ import annotations

import logging
from typing import Any

import httpx

from govcrawler.settings import get_settings

log = logging.getLogger(__name__)

DEFAULT_TIMEOUT_S = 10.0


def build_payload(text: str, provider: str) -> dict[str, Any]:
    """Shape the outbound JSON per provider. Raises on unknown provider."""
    p = provider.lower()
    if p == "feishu":
        return {"msg_type": "text", "content": {"text": text}}
    if p in ("wechat", "wechat_work", "wecom"):
        return {"msgtype": "text", "text": {"content": text}}
    raise ValueError(f"unknown alert_provider: {provider!r}")


def send_alert(text: str, *, url: str | None = None, provider: str | None = None) -> bool:
    """Post a text alert. Returns True on HTTP 2xx, False otherwise.

    `url`/`provider` override settings — useful for tests and for per-severity
    routing once we add multiple channels. Empty URL = alerting disabled
    (returns False without attempting the POST).
    """
    settings = get_settings()
    target = url if url is not None else settings.alert_webhook_url
    prov = provider if provider is not None else settings.alert_provider

    if not target:
        log.debug("alerting disabled (no webhook_url)")
        return False

    payload = build_payload(text, prov)
    try:
        r = httpx.post(target, json=payload, timeout=DEFAULT_TIMEOUT_S)
    except Exception as e:
        log.warning("alert POST failed: %s", e)
        return False

    if 200 <= r.status_code < 300:
        return True
    log.warning("alert POST rejected status=%s body=%s", r.status_code, r.text[:200])
    return False
