#!/usr/bin/env python3
import argparse
import json
import os
import sys
import urllib.request


def main() -> int:
    parser = argparse.ArgumentParser(description="Post a message to Slack channel #rob-feed")
    parser.add_argument("--text", help="Message text to post")
    parser.add_argument("--stdin", action="store_true", help="Read message text from stdin")
    args = parser.parse_args()

    if args.stdin:
        text = sys.stdin.read()
    else:
        text = args.text

    if text is None or not text.strip():
        print("error: provide --text or --stdin with non-empty content", file=sys.stderr)
        return 2

    token = os.environ.get("SLACK_BOT_TOKEN")
    channel = os.environ.get("SLACK_ROB_FEED_CHANNEL_ID")
    if not token:
        print("error: missing SLACK_BOT_TOKEN", file=sys.stderr)
        return 2
    if not channel:
        print("error: missing SLACK_ROB_FEED_CHANNEL_ID", file=sys.stderr)
        return 2

    payload = {"channel": channel, "text": text.strip()}
    req = urllib.request.Request(
        "https://slack.com/api/chat.postMessage",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json; charset=utf-8",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            body = resp.read().decode()
    except Exception as exc:
        print(f"error: slack request failed: {exc}", file=sys.stderr)
        return 1

    print(body)
    try:
        data = json.loads(body)
    except Exception:
        return 1
    return 0 if data.get("ok") else 1


if __name__ == "__main__":
    raise SystemExit(main())
