#!/usr/bin/env python3
"""Minimal PushNotifications.org REST API client. Python 3.10+; no dependencies."""

import argparse
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request


def request(method, path, payload=None, query=None):
    token = os.environ.get("PUSHNOTIFICATIONS_TOKEN", "").strip()
    if not token.startswith("pn_"):
        raise SystemExit("Set PUSHNOTIFICATIONS_TOKEN to an account API token.")
    base = os.environ.get("PUSHNOTIFICATIONS_API", "https://pushnotifications.org/api/v1").rstrip("/")
    url = f"{base}/{path.lstrip('/')}"
    if query:
        url += "?" + urllib.parse.urlencode({key: value for key, value in query.items() if value is not None})
    data = json.dumps(payload).encode() if payload is not None else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Authorization", f"Bearer {token}")
    req.add_header("Accept", "application/json")
    if data is not None:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=30) as response:
            return json.load(response)
    except urllib.error.HTTPError as error:
        try:
            detail = json.load(error)
        except (ValueError, json.JSONDecodeError):
            detail = {"error": f"HTTP {error.code}"}
        raise SystemExit(json.dumps(detail, indent=2)) from error
    except urllib.error.URLError as error:
        raise SystemExit(f"Connection failed: {error.reason}") from error


def parser():
    root = argparse.ArgumentParser(description="Review PushNotifications.org data and create campaign drafts.")
    commands = root.add_subparsers(dest="command", required=True)
    commands.add_parser("sites", help="List registered websites.")
    commands.add_parser("overview", help="Show delivery usage and campaign counts.")
    campaigns = commands.add_parser("campaigns", help="List campaigns.")
    campaigns.add_argument("--site", type=int)
    campaigns.add_argument("--status", choices=("draft", "scheduled", "sending", "sent", "paused", "failed"))
    campaigns.add_argument("--limit", type=int, default=25, choices=range(1, 101), metavar="1-100")
    campaign = commands.add_parser("campaign", help="Get one campaign.")
    campaign.add_argument("id", type=int)
    draft = commands.add_parser("create-draft", help="Create a reviewable campaign draft.")
    draft.add_argument("--site", type=int, required=True)
    draft.add_argument("--title", required=True)
    draft.add_argument("--body", required=True)
    draft.add_argument("--url", required=True)
    draft.add_argument("--image-url")
    return root


def main():
    args = parser().parse_args()
    if args.command == "sites":
        result = request("GET", "sites")
    elif args.command == "overview":
        result = request("GET", "overview")
    elif args.command == "campaigns":
        result = request("GET", "campaigns", query={"site": args.site, "status": args.status, "limit": args.limit})
    elif args.command == "campaign":
        result = request("GET", f"campaigns/{args.id}")
    else:
        payload = {"site_id": args.site, "title": args.title, "body": args.body, "target_url": args.url, "status": "draft"}
        if args.image_url:
            payload["image_url"] = args.image_url
        result = request("POST", "campaigns", payload=payload)
    print(json.dumps(result, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()
