from __future__ import annotations

import json
import socket
import time

import requests
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Test Hously system notifications webhook (HTTP) like an external server."

    def add_arguments(self, parser):
        parser.add_argument(
            "--base-url",
            type=str,
            required=True,
            help="Hously base url, e.g. https://www.hously.cloud",
        )
        parser.add_argument(
            "--webhook-key",
            type=str,
            required=True,
            help="RAW webhook key (X-Webhook-Key).",
        )
        parser.add_argument(
            "--topic",
            type=str,
            required=True,
            help="Topic code, e.g. api_500_registration",
        )
        parser.add_argument(
            "--severity",
            type=str,
            default="info",
            help="info|warning|error|critical",
        )
        parser.add_argument("--title", type=str, default="", help="Optional title")
        parser.add_argument("--text", type=str, default="", help="Optional text")
        parser.add_argument(
            "--payload",
            type=str,
            default="",
            help='Optional JSON payload string, e.g. \'{"service":"test","count":1}\'',
        )
        parser.add_argument("--timeout", type=float, default=8.0, help="HTTP timeout in seconds")

    def handle(self, *args, **opts):
        base_url = (opts["base_url"] or "").strip().rstrip("/")
        webhook_key = (opts["webhook_key"] or "").strip()
        topic = (opts["topic"] or "").strip()
        severity = (opts["severity"] or "info").strip()
        title = (opts["title"] or "").strip()
        text = (opts["text"] or "").strip()
        payload_raw = (opts["payload"] or "").strip()
        timeout = float(opts["timeout"])

        if not base_url or not webhook_key or not topic:
            self.stderr.write(self.style.ERROR("Missing required args: --base-url --webhook-key --topic"))
            return

        extra = {}
        if payload_raw:
            try:
                extra = json.loads(payload_raw)
                if not isinstance(extra, dict):
                    extra = {"_payload": extra}
            except Exception as e:
                self.stderr.write(self.style.ERROR(f"Invalid JSON in --payload: {e}"))
                return

        # helpful defaults
        extra.setdefault("host", socket.gethostname())
        extra.setdefault("ts", int(time.time()))
        extra.setdefault("source", "django-command-external-test")

        if not title:
            title = "✅ Webhook test (external)"
        if not text:
            text = "If you received this, webhook key + routing works."

        url = f"{base_url}/system/webhooks/system-events/"
        body = {
            "topic_code": topic,
            "severity": severity,
            "title": title,
            "text": text,
            "payload": extra,
        }

        headers = {
            "X-Webhook-Key": webhook_key,
            "Content-Type": "application/json",
            "User-Agent": "hously-webhook-test/1.0",
        }

        try:
            r = requests.post(url, headers=headers, data=json.dumps(body), timeout=timeout)
        except Exception as e:
            self.stderr.write(self.style.ERROR(f"Request failed: {e}"))
            return

        self.stdout.write(f"URL: {url}")
        self.stdout.write(f"Status: {r.status_code}")
        self.stdout.write("Response:")
        self.stdout.write(r.text[:2000])

        if r.status_code < 200 or r.status_code >= 300:
            self.stderr.write(self.style.ERROR("❌ Webhook test failed (non-2xx)."))
            return

        self.stdout.write(self.style.SUCCESS("✅ Webhook test succeeded"))




# python manage.py notify_test `
#   --base-url "https://www.hously.cloud" `
#   --webhook-key "SeHRjjVK1vFMYfQ1iIq8--AAmKDBvheNbguMQ2q1MnCKsndJjG6ZWcmx8--J3YzL" `
#   --topic "nm" `
#   --severity "info" `
#   --title "✅ Test z innego serwera" `
#   --text "Jeśli to widzisz, webhook działa" `
