from __future__ import annotations

from pathlib import Path
from typing import Any

import requests

from . import Alert


class DiscordNotifier:
    name = "discord"

    def __init__(self, webhook_url: str, session: Any = None) -> None:
        self._url = webhook_url
        self._session = session or requests.Session()

    def send(self, alert: Alert) -> None:
        content = f"**{alert.title}**\n{alert.body}"

        if alert.image_path and Path(alert.image_path).exists():
            with open(alert.image_path, "rb") as fh:
                resp = self._session.post(
                    self._url,
                    data={"content": content},
                    files={"file": fh},
                    timeout=10,
                )
        else:
            resp = self._session.post(
                self._url,
                json={"content": content},
                timeout=10,
            )

        if resp.status_code == 429:
            raise RuntimeError(f"Discord rate-limited (429): {resp.text}")
        if resp.status_code >= 500:
            raise RuntimeError(f"Discord server error ({resp.status_code}): {resp.text}")
        # 200 / 204 are OK; other 4xx are treated as errors too
        if not (resp.status_code in (200, 204)):
            raise RuntimeError(f"Discord unexpected status ({resp.status_code}): {resp.text}")
