"""Send operator-only Telegram notifications."""

from __future__ import annotations

import os
import time
from pathlib import Path
from collections.abc import Iterable

import requests


ROOT = Path(__file__).resolve().parent
TELEGRAM_KEYS = (
    "PCOS_TG_BOT_TOKEN",
    "PCOS_TG_CHAT_ID",
)


def env_path() -> Path:
    """Where the secrets live.

    On the laptop that is `.env` beside the code. On the box there is no `.env`: systemd
    decrypts the credential into a private tmpfs and passes the path in PCOS_ENV_FILE,
    so the same code runs both places and neither has a plaintext secret sitting in the
    working directory.
    """
    override = os.environ.get("PCOS_ENV_FILE")
    return Path(override) if override else ROOT / ".env"


def read_env() -> dict[str, str]:
    values: dict[str, str] = {}
    path = env_path()
    if path.exists():
        for raw_line in path.read_text(encoding="utf-8").splitlines():
            line = raw_line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            values[key.strip()] = value.strip()

    values.update(os.environ)
    return values


def load_env(required: Iterable[str] = TELEGRAM_KEYS) -> dict[str, str]:
    values = read_env()
    missing = [key for key in required if not values.get(key)]
    if missing:
        raise RuntimeError("Missing required environment keys: " + ", ".join(missing))
    return values


def redact_secrets(text: str) -> str:
    """Remove configured credential values before text is logged or notified."""
    redacted = text
    for key, value in read_env().items():
        if value and ("PASSWORD" in key or "TOKEN" in key):
            redacted = redacted.replace(value, "[REDACTED]")
            redacted = redacted.replace(value.replace(" ", ""), "[REDACTED]")
    return redacted


def send(text: str) -> bool:
    """Send text to the single configured operator chat."""
    config = load_env(TELEGRAM_KEYS)
    url = f"https://api.telegram.org/bot{config['PCOS_TG_BOT_TOKEN']}/sendMessage"
    payload = {"chat_id": config["PCOS_TG_CHAT_ID"], "text": text}

    for attempt in range(3):
        try:
            response = requests.post(url, data=payload, timeout=20)
            response.raise_for_status()
            # Print the receipt. "It returned True" is not evidence a message landed
            # on his phone; a message_id from Telegram is. House rule: no artefact,
            # no claim. The id is not a secret and the token is never printed.
            try:
                message_id = response.json().get("result", {}).get("message_id")
                print(f"Telegram accepted: message_id={message_id}")
            except ValueError:
                print("Telegram accepted (no JSON body returned)")
            return True
        except requests.RequestException:
            if attempt < 2:
                time.sleep(2**attempt)

    print("Telegram notification failed after three attempts.")
    return False
