#!/usr/bin/env python3
"""arq-slack — Slack API bridge.
v0: arq-slack channel list · arq-slack message post --channel <C> --text <T>
"""
import argparse, json, os, sys, urllib.request, urllib.error
from urllib.parse import urlencode
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from _arq_provider_base import sops_extract, call_with_audit, print_json, handle_meta_flags

PROVIDER = "slack"
REQUIRED_SCOPES: dict[str, list[str]] = {
    # Slack bot-token scopes (https://api.slack.com/scopes).
    "channel list": ["channels:read", "groups:read", "mpim:read", "im:read"],
    "message post": ["chat:write"],
}
def _key(): return os.environ.get("SLACK_BOT_TOKEN") or sops_extract('["arqera_twin_admin"]["slack"]["value"]') or sops_extract('["slack"]["slack_bot_token"]')
def _get(path):
    k = _key()
    if not k: return 401, "no slack token"
    req = urllib.request.Request(f"https://slack.com/api{path}", headers={"Authorization": f"Bearer {k}"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e: return e.code, e.read().decode("utf-8","ignore")
    except Exception as e: return 500, str(e)
def _post(path, data):
    k = _key()
    if not k: return 401, "no slack token"
    req = urllib.request.Request(f"https://slack.com/api{path}", data=urlencode(data).encode(), headers={"Authorization": f"Bearer {k}", "Content-Type": "application/x-www-form-urlencoded"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e: return e.code, e.read().decode("utf-8","ignore")
    except Exception as e: return 500, str(e)

def _chans(a):
    c, d = _get("/conversations.list?limit=100&exclude_archived=true")
    if c != 200: sys.stderr.write(f"HTTP {c}: {d}\n"); return 1
    return print_json(d)
def _msg(a):
    c, d = _post("/chat.postMessage", {"channel": a.channel, "text": a.text})
    if c != 200: sys.stderr.write(f"HTTP {c}: {d}\n"); return 1
    return print_json(d)

def main():
    handle_meta_flags(PROVIDER, REQUIRED_SCOPES)
    p = argparse.ArgumentParser(prog="arq-slack"); s = p.add_subparsers(dest="cmd", required=True)
    sc = s.add_parser("channel"); sc2 = sc.add_subparsers(dest="action", required=True)
    sc2.add_parser("list").set_defaults(func=_chans, verb="channel list")
    sm = s.add_parser("message"); sm2 = sm.add_subparsers(dest="action", required=True)
    smp = sm2.add_parser("post"); smp.add_argument("--channel", required=True); smp.add_argument("--text", required=True); smp.set_defaults(func=_msg, verb="message post")
    args = p.parse_args()
    return call_with_audit(PROVIDER, args.verb, args.func, args)

if __name__ == "__main__": sys.exit(main())
